Why no ICloneable<T>? - c#

Is there a particular reason why a generic ICloneable<T> does not exist?
It would be much more comfortable, if I would not need to cast it everytime I clone something.

In addition to Andrey's reply (which I agree with, +1) - when ICloneable is done, you can also choose explicit implementation to make the public Clone() return a typed object:
public Foo Clone() { /* your code */ }
object ICloneable.Clone() {return Clone();}
Of course there is a second issue with a generic ICloneable<T> - inheritance.
If I have:
public class Foo {}
public class Bar : Foo {}
And I implemented ICloneable<T>, then do I implement ICloneable<Foo>? ICloneable<Bar>? You quickly start implementing a lot of identical interfaces...
Compare to a cast... and is it really so bad?

ICloneable is considered a bad API now, since it does not specify whether the result is a deep or a shallow copy. I think this is why they do not improve this interface.
You can probably do a typed cloning extension method, but I think it would require a different name since extension methods have less priority than original ones.

I need to ask, what exactly would you do with the interface other than implement it? Interfaces are typically only useful when you cast to it (ie does this class support 'IBar'), or have parameters or setters that take it (ie i take an 'IBar'). With ICloneable - we went through the entire Framework and failed to find a single usage anywhere that was something other than an implementation of it. We've also failed to find any usage in the 'real world' that also does something other than implement it (in the ~60,000 apps that we have access to).
Now if you would just like to enforce a pattern that you want your 'cloneable' objects to implement, that's a completely fine usage - and go ahead. You can also decide on exactly what "cloning" means to you (ie deep or shallow). However, in that case, there's no need for us (the BCL) to define it. We only define abstractions in the BCL when there is a need to exchange instances typed as that abstraction between unrelated libraries.
David Kean (BCL Team)

I think the question "why" is needless. There is a lot of interfaces/classes/etc... which is very usefull, but is not part of .NET Frameworku base library.
But, mainly you can do it yourself.
public interface ICloneable<T> : ICloneable {
new T Clone();
}
public abstract class CloneableBase<T> : ICloneable<T> where T : CloneableBase<T> {
public abstract T Clone();
object ICloneable.Clone() => return this.Clone();
}
public abstract class CloneableExBase<T> : CloneableBase<T> where T : CloneableExBase<T> {
protected abstract T CreateClone();
protected abstract void FillClone(T clone);
public override T Clone() {
T clone = this.CreateClone();
if (clone is null ) {
throw new NullReferenceException( "Clone was not created." );
}
this.FillClone(clone);
return clone
}
}
public abstract class PersonBase<T> : CloneableExBase<T> where T : PersonBase<T> {
public string Name { get; set; }
protected override void FillClone( T clone ) {
clone.Name = this.Name;
}
}
public sealed class Person : PersonBase<Person> {
protected override Person CreateClone() => return new Person();
}
public abstract class EmployeeBase<T> : PersonBase<T> where T : EmployeeBase<T> {
public string Department { get; set; }
protected override void FillClone(T clone) {
base.FillClone(clone);
clone.Department = this.Department;
}
}
public sealed class Employee : EmployeeBase<Employee> {
protected override Employee CreateClone() => return new Employee();
}

It's pretty easy to write the interface yourself if you need it:
public interface ICloneable<T> : ICloneable
where T : ICloneable<T>
{
new T Clone();
}

Having read recently the article Why Copying an Object is a terrible thing to do?, I think this question needs additional clafirication. Other answers here provide good advices, but still the answer isn't complete - why no ICloneable<T>?
Usage
So, you have a class that implements it. While previously you had a method that wanted ICloneable, it now has to be generic to accept ICloneable<T>. You would need to edit it.
Then, you could have got a method that checks if an object is ICloneable. What now? You can't do is ICloneable<> and as you don't know the type of the object at compile-type, you can't make the method generic. First real problem.
So you need to have both ICloneable<T> and ICloneable, the former implementing the latter. Thus an implementer would need to implement both methods - object Clone() and T Clone(). No, thanks, we already have enough fun with IEnumerable.
As already pointed out, there is also the complexity of inheritance. While covariance may seem to solve this problem, a derived type needs to implement ICloneable<T> of its own type, but there is already a method with the same signature (= parameters, basically) - the Clone() of the base class. Making your new clone method interface explicit is pointless, you will lose the advantage you sought when creating ICloneable<T>. So add the new keyword. But don't forget that you would also need to override the base class' Clone() (the implementation has to remain uniform for all derived classes, i.e. to return the same object from every clone method, so the base clone method has to be virtual)! But, unfortunately, you can't both override and new methods with the same signature. Choosing the first keyword, you'd lose the goal you wanted to have when adding ICloneable<T>. Chossing the second one, you'd break the interface itself, making methods that should do the same return different objects.
Point
You want ICloneable<T> for comfort, but comfort is not what interfaces are designed for, their meaning is (in general OOP) to unify the behavior of objects (although in C#, it is limited to unifying the outer behavior, e.g. the methods and properties, not their workings).
If the first reason hasn't convinced you yet, you could object that ICloneable<T> could also work restrictively, to limit the type returned from the clone method. However, nasty programmer can implement ICloneable<T> where T is not the type that is implementing it. So, to achieve your restriction, you can add a nice constraint to the generic parameter:
public interface ICloneable<T> : ICloneable where T : ICloneable<T>
Certainly more restrictive that the one without where, you still can't restrict that T is the type that is implementing the interface (you can derive from ICloneable<T> of different type that implements it).
You see, even this purpose couldn't be achieved (the original ICloneable also fails at this, no interface can truly limit the behavior of the implementing class).
As you can see, this proves making the generic interface is both hard to fully implement and also really unneeded and useless.
But back to the question, what you really seek is to have comfort when cloning an object. There are two ways to do it:
Additional methods
public class Base : ICloneable
{
public Base Clone()
{
return this.CloneImpl() as Base;
}
object ICloneable.Clone()
{
return this.CloneImpl();
}
protected virtual object CloneImpl()
{
return new Base();
}
}
public class Derived : Base
{
public new Derived Clone()
{
return this.CloneImpl() as Derived;
}
protected override object CloneImpl()
{
return new Derived();
}
}
This solution provides both comfort and intended behavior to users, but it's also too long to implement. If we didn't want to have the "comfortable" method returning the current type, it is much more easy to have just public virtual object Clone().
So let's see the "ultimate" solution - what in C# is really intented to give us comfort? Extension methods!
public class Base : ICloneable
{
public virtual object Clone()
{
return new Base();
}
}
public class Derived : Base
{
public override object Clone()
{
return new Derived();
}
}
public static T Copy<T>(this T obj) where T : class, ICloneable
{
return obj.Clone() as T;
}
It's named Copy not to collide with the current Clone methods (compiler prefers the type's own declared methods over extension ones). The class constraint is there for speed (doesn't require null check etc.).
I hope this clarifies the reason why not to make ICloneable<T>. However, it is recommended not to implement ICloneable at all.

A big problem is that they could not restrict T to be the same class. Fore example what would prevent you from doing this:
interface IClonable<T>
{
T Clone();
}
class Dog : IClonable<JackRabbit>
{
//not what you would expect, but possible
JackRabbit Clone()
{
return new JackRabbit();
}
}
They need a parameter restriction like:
interfact IClonable<T> where T : implementing_type

It's a very good question... You could make your own, though:
interface ICloneable<T> : ICloneable
{
new T Clone ( );
}
Andrey says it's considered a bad API, but i have not heard anything about this interface becoming deprecated. And that would break tons of interfaces...
The Clone method should perform a shallow copy.
If the object also provides deep copy, an overloaded Clone ( bool deep ) can be used.
EDIT: Pattern i use for "cloning" an object, is passing a prototype in the constructor.
class C
{
public C ( C prototype )
{
...
}
}
This removes any potential redundant code implementation situations.
BTW, talking about the limitations of ICloneable, isn't it really up to the object itself to decide whether a shallow clone or deep clone, or even a partly shallow/partly deep clone, should be performed? Should we really care, as long as the object works as intended? In some occasions, a good Clone implementation might very well include both shallow and deep cloning.

Related

Why calling method on interface uses base implementation instead of override?

I have a problem with my code.
I would expect that since I'm constructing the Implementation object; every time I call Method() I'd use actual Implementation.Method() and not it's abstract's Base.Method(). It does not seem reasonable that I have to downcast to actual implementer or specify interface explicitly (So interfaces are not transitive in C#? I will call the "first proper instance of interface implementer" and not my class?)
I have a structure similar to this (simplified for clarity):
https://dotnetfiddle.net/oYVlQO
using System;
public interface IBase
{
string Method();
}
public abstract class Base : IBase
{
public string Method() { return "Sample"; }
}
public class Implementation : Base // if I add ", IBase" to this it works as expected, but why?
{
new public string Method() { return "Overriden"; }
}
public class Program
{
// and it's used like so...
public static void Main()
{
IBase b = new Implementation();
//Implementation b = new Implementation(); // It works as expected, always using Implementation.Method();
Console.WriteLine(b.Method()); // Produces "Sample", so Base.Method(). Why not implementation?
Console.WriteLine(((Implementation) b).Method()); // Produces "Overriden", so Implementation.Method(); Since when I have to downcast to use overriden method!?
}
}
}
I'm really scratching my head over this; Especially that the same code in Java works "as I would expect" https://repl.it/repls/VitalSpiritedWebpage
I've tried to find it in the c# specs to no avail, maybe I do not have the proper keywords...
In cause of the question, which is:
Why is it that way?
My answer:
Because you don’t override the method but hide it.
The interface is implemented by the baseclass, so the Method is called on the base-class.
To answer the question, which isn’t asked:
How would it work?
Answer:
using System;
public interface IBase
{
string Method();
}
public abstract class Base : IBase
{
public virtual string Method() { return "Sample"; }
}
public class Implementation : Base
{
public override string Method() { return "Overriden"; }
}
You may want to take a look at the part of the C# spec that deals with interface re-implementation.
When you access a member through the interface, it begins its lookup at the most derived type that explicitly implements that interface. In your example, the most derived type is Base and so it calls the method that's present there.
When you added IBase to the list of interfaces explicitly implemented by Implementation it worked, because that's the new starting point for lookup and it finds your new method.
You can either solve your problem by making the base member virtual and then overriding it in derived classes, or you can re-implement the interface by including that in the list for your Implementation class.
So the problem in my sample code is two-fold.
I assumed that in C# methods are "virtual" by default (as is in Java). Since I'm usually coding in Java, I've made an incorrect assumption.
See Is it possible to override a non-virtual method?
If I'd use virtual, I could override the method and achieve exactly the output I expected, as described in doc:
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/virtual namely "When a virtual method is invoked, the run-time type of the object is checked for an overriding member. The overriding member in the most derived class is called, which might be the original member, if no derived class has overridden the member."
My code, hovewer, is using method hiding, so unless I inform the compiler about my intention of using my implementation, it'll default to non-hidden method (as resolved by abstract class being the actual, original implementer)

Creating an abstract generic method

I have a C# class with a method such as below:
public class MyType
{
public MyType Clone()
{
var clone = (MyType)MemberwiseClone();
// Do some other stuff here with the clone's properties
return clone;
}
}
I have a bunch of other classes where I want to implement the Clone method so I was thinking I could create an abstract base class where I could define the Clone method generically so I don't have to put a concrete implementation in each class.
I would think this is possible but I haven't worked too much with generics and my attempts to do this in the past (months ago, so discarded my code out of frustration) haven't been successful.
Is this possible? If so, how could it be done?
Create an abstract generic base and then implement the concrete type on the derived ones:
public abstract class ClonableBase<T>
{
public T Clone()
{
return (T)this.MemberwiseClone();
}
}
public class RealClass : ClonableBase<RealClass> { }
The usefulness of this approach depends significantly on what it is that you're cloning.
Here's a method that I use. The cloning method is a bit crude. It's specifically for objects that are meant to be serialized as JSON.
That's why the generic constraint (TEntity : BaseEntity) is there. I don't want just anything passed into this method, only something that I know is serializable.
I also avoided using the generic argument for JsonConvert.DeserializeObject because while I want to cast the result as a specific type, I don't want to pass in an inherited type and get back an instance of a base type.
public static TEntity CloneEntity<TEntity>(this BaseEntity input) where TEntity
: BaseEntity
{
if (input == null) return null;
var serialized = JsonConvert.SerializeObject(input);
return (TEntity)JsonConvert.DeserializeObject(serialized, input.GetType());
}
Although it's already been accepted, I don't recommend adding this to a base class unless absolutely necessary. Before long you might find that you need to clone something that already inherits from a different base class.
This requires the Newtonsoft.JSON package.
As mentioned in a comment, this will do a deep clone. As I stated at the top, this method applies only if serialization/deserialization cloning is appropriate to the types you need to clone. If there were a universally applicable way to clone objects that applied in every case then object would probably have a public Clone method.
If we're cloning classes it's likely because they contain data, and where that's the case deep cloning is likely preferable. For example, suppose we have a Customer class, and one if its properties exposes an Address object. MemberwiseClone will clone the value types, but will result in two Customer objects that share a reference to the same Address. If we're cloning it's usually because we're trying to create entirely distinct objects. If we think we've cloned something but beneath the surface the original and clone share object references then there's a good chance we'll have bugs.
Built on #Gusman's solution I add the possibility to do some initialization
public abstract class ClonableBase<T>
{
public T Clone()
{
T clone = (T)MemberwiseClone();
Initialize(clone)
return clone;
}
protected virtual void Initialize(T clone)
{
}
}
If the initialization is mandatory, you can also make Initialize abstract instead.
public class RealClass : ClonableBase<RealClass> {
protected override void Initialize(T clone)
{
// Do some other stuff here with the clone's properties
}
}

Downcasting this in an abstract base-class, is there any way to force it?

Is there anyway to force a downcast in the abstract base-class when the derived type is actually known there (due to complicated generics)?
Right now my ugly workaround is to implement an abstract protected property This that simply return this... so the usual stuff about downcasting not being possible due to "missing extra parts" dont apply, all parts are there, I just have to force the type-system to cut me some slack :/
protected abstract T This { get; }
I know the derived type, I just cant find any way to force the cast to happen!
Is there any way at all?
(This is part of a framework so forcing the consumer to implement silly things like a This-property really sucks. I would rather make the inner workings more complex, and force the consumer to write as little code as possible.)
Edit:
Since it's hard to see what good this would do, I will try to add some more code. It will still look weird perhaps, I will try to add more again if needed.
Basically in this specific problem part of the code it involves two methods in this fashion (actual implementation details omitted, just an illustration)
abstract class Base<DerivedType, OtherType>
where .... //Complicated constraints omitted
{
protected abstract OtherType Factory(DerivedType d);
public bool TryCreate(out OtherType o)
{
//Omitted some dependency on fields that reside in the base and other stuff
//if success...
o = Factory((DerivedType)this); //<-- what I can not do
return true;
}
}
(As for the bigger picture it is part of a strongly typed alternative to some of the things you can do with xpath, working on top of Linq2Xml.)
The following class definition compiles. I don't know whether your omitted constraints would conflict with this.
public abstract class Base<DerivedType, OtherType>
where DerivedType : Base<DerivedType, OtherType>
{
protected abstract OtherType Factory(DerivedType d);
public bool TryCreate(out OtherType o)
{
o = Factory ((DerivedType)this);
return true;
}
}
public class MyClass : Base<MyClass, string>
{
protected override string Factory (MyClass d)
{
return d.GetType ().Name;
}
}

C# generic factory method

Perhaps this is a simple newbie C# question, but so be it---it will be a fresh break from my other questions, which are so difficult that no one knows the answer to them. :)
Let's say I have a generic type in C#:
Thing<T>
And let's say I want to make a thing using a static factory method. In Java, this is no problem:
public static <T> Thing<T> createThing()
{
return flag ? new Thing<Integer>(5) : new Thing<String>("hello");
}
How do I do this in C#? Thanks.
If you want to return an instance of a templated class using one of many different template arguments, one way to do it is with an abstract base (or an interface):
abstract class UntypedThing { }
class Thing<T> : UntypedThing
{
public Thing(T t) { }
}
class Foo
{
public static UntypedThing createThing(bool flag)
{
if (flag)
return new Thing<int>(5);
else return new Thing<String>("hello");
}
}
The UntypedThing class would contain as much code as possible that does not rely on the template type. The Thing class would ideally only contain code that relies on the template type. The factory class Foo always returns the former.
You can in theory use reflection to build up the correct generic type, but it will be pretty useless to you as at some point you will need to upcast it to a less specific type.
public class ThingFactory {
public object Create(bool flag) {
Type outputType = null;
if(flag) {
outputType = typeof(string);
} else {
outputType = typeof(int);
}
return Activator.CreateInstance(typeof(Thing<>).MakeGenericType(outputType));
}
}
As you can see, the value of doing this is about zero as you will need to cast the return type to the type you want, meaning that the logic to determine it needs to live outside the Create method.
I would use Reinderien's method and have a non-generic base. This is the most sane and idiomatic approach.
Oh, the trouble I get myself in when I simply try to do something simple.
It turns out that C# 4 allows this sort of covariance---sort of. First, I have to make Thing an interface and specify the "out" generic parameter:
public interface Thing<out T> {...}
But if I do certain things, C# won't let me use covariance. For example, if I try to return T from the interface:
public interface Thing<out T>
{
public T GetT();
Even if I manage to get covariance with Thing, what do I do with it?
Thing<object> thing=createThing();
The compiler tells me that the type cannot be inferred from usage.
Let's say I say screw the whole T thing and make the factory method return Thing of type object:
public static Thing<object> createThing() {...}
Fine, but now where do I put it?
IList<Thing<object>> list=new List<Thing<object>>();
Thing<object> thing=createThing();
list.Add(thing);
Yes, I have to say that this is a list of Thing with T of type Object, because C# has no wildcard type.
If this were Java, I'd simply say:
public class Thing<T> {...}
public static <T> Thing<T> createThing() {...}
List<?> things=new ArrayList<Thing<?>>();
Thing<?> thing=createThing();
things.add(thing);
If I wanted extra safety by saying that T had to be of a special type, I'd say:
public static <T extends MyBaseType> Thing<T> createThing() {...}
List<? extends MyBaseType> things=new ArrayList<Thing<? extends MyBaseType>>();
Thing<? extends MyBaseType> thing=createThing();
things.add(thing);
Then I'd figure out what T is later, when I had more information.
This all seems to come down to incomplete generic covariance in C# coupled with the lack of C# generic wildcards. (I still maintain it isn't an erasure issue.)
So what do I do? The only simple thing to do seems to follow Reinderien's answer and split out a non-generic base class.
(I wonder if in this non-generic base class I could have object getValue() and then use covariance in the subclass to return T getValue()? Ack, I'm tired of this---I'll leave that for another day.)

Using Interface variables

I'm still trying to get a better understanding of Interfaces. I know about what they are and how to implement them in classes.
What I don't understand is when you create a variable that is of one of your Interface types:
IMyInterface somevariable;
Why would you do this? I don't understand how IMyInterface can be used like a class...for example to call methods, so:
somevariable.CallSomeMethod();
Why would you use an IMyInterface variable to do this?
You are not creating an instance of the interface - you are creating an instance of something that implements the interface.
The point of the interface is that it guarantees that what ever implements it will provide the methods declared within it.
So now, using your example, you could have:
MyNiftyClass : IMyInterface
{
public void CallSomeMethod()
{
//Do something nifty
}
}
MyOddClass : IMyInterface
{
public void CallSomeMethod()
{
//Do something odd
}
}
And now you have:
IMyInterface nifty = new MyNiftyClass()
IMyInterface odd = new MyOddClass()
Calling the CallSomeMethod method will now do either something nifty or something odd, and this becomes particulary useful when you are passing in using IMyInterface as the type.
public void ThisMethodShowsHowItWorks(IMyInterface someObject)
{
someObject.CallSomeMethod();
}
Now, depending on whether you call the above method with a nifty or an odd class, you get different behaviour.
public void AnotherClass()
{
IMyInterface nifty = new MyNiftyClass()
IMyInterface odd = new MyOddClass()
// Pass in the nifty class to do something nifty
this.ThisMethodShowsHowItWorks(nifty);
// Pass in the odd class to do something odd
this.ThisMethodShowsHowItWorks(odd);
}
EDIT
This addresses what I think your intended question is - Why would you declare a variable to be of an interface type?
That is, why use:
IMyInterface foo = new MyConcreteClass();
in preference to:
MyConcreteClass foo = new MyConcreteClass();
Hopefully it is clear why you would use the interface when declaring a method signature, but that leaves the question about locally scoped variables:
public void AMethod()
{
// Why use this?
IMyInterface foo = new MyConcreteClass();
// Why not use this?
MyConcreteClass bar = new MyConcreteClass();
}
Usually there is no technical reason why the interface is preferred. I usually use the interface because:
I typically inject dependencies so the polymorphism is needed
Using the interface clearly states my intent to only use members of the interface
The one place where you would technically need the interface is where you are utilising the polymorphism, such as creating your variable using a factory or (as I say above) using dependency injection.
Borrowing an example from itowlson, using concrete declaration you could not do this:
public void AMethod(string input)
{
IMyInterface foo;
if (input == "nifty")
{
foo = new MyNiftyClass();
}
else
{
foo = new MyOddClass();
}
foo.CallSomeMethod();
}
Because this:
public void ReadItemsList(List<string> items);
public void ReadItemsArray(string[] items);
can become this:
public void ReadItems(IEnumerable<string> items);
Edit
Think of it like this:
You have to be able to do this.
rather than:
You have to be this.
Essentially this is a contract between the method and it's callers.
Using interface variables is the ONLY way to allow handler methods to be written which can accept data from objects that have different base classes.
This is about as clear as anyone is going to get.
An interface is used so you do not need to worry about what class implements the interface. An example of this being useful is when you have a factory method that returns a concrete implementation that may be different depending on the environment you are running in. It also allows an API designer to define the API while allowing 3rd parties to implement the API in any way they see fit. Sun does this with it's cryptographic API's for Java.
public interface Foo {
}
public class FooFactory {
public static Foo getInstance() {
if(os == 'Windows') return new WinFoo();
else if(os == 'OS X') return new MacFoo();
else return new GenricFoo();
}
}
Your code that uses the factory only needs to know about Foo, not any of the specific implementations.
I was in same position and took me few days to figure out why do we have to use interface variable.
IDepartments rep = new DepartmentsImpl();
why not
DepartmentsImpl rep = new DepartmentsImpl();
Imagine If a class implements two interfaces that contain a member with the same signature, then implementing that member on the class will cause both interfaces to use that member as their implementation.
class Test
{
static void Main()
{
SampleClass sc = new SampleClass();
IControl ctrl = (IControl)sc;
ISurface srfc = (ISurface)sc;
// The following lines all call the same method.
sc.Paint();
ctrl.Paint();
srfc.Paint();
}
}
interface IControl
{
void Paint();
}
interface ISurface
{
void Paint();
}
class SampleClass : IControl, ISurface
{
// Both ISurface.Paint and IControl.Paint call this method.
public void Paint()
{
Console.WriteLine("Paint method in SampleClass");
}
}
// Output:
// Paint method in SampleClass
// Paint method in SampleClass
// Paint method in SampleClass
If the two interface members do not perform the same function, however, this can lead to an incorrect implementation of one or both of the interfaces.
public class SampleClass : IControl, ISurface
{
void IControl.Paint()
{
System.Console.WriteLine("IControl.Paint");
}
void ISurface.Paint()
{
System.Console.WriteLine("ISurface.Paint");
}
}
The class member IControl.Paint is only available through the IControl interface, and ISurface.Paint is only available through ISurface. Both method implementations are separate, and neither is available directly on the class. For example:
IControl c = new SampleClass();
ISurface s = new SampleClass();
s.Paint();
Please do correct me if i am wrong as i am still learning this Interface concept.
Lets say you have class Boat, Car, Truck, Plane.
These all share a common method TakeMeThere(string destination)
You would have an interface:
public interface ITransportation
{
public void TakeMeThere(string destination);
}
then your class:
public class Boat : ITransportation
{
public void TakeMeThere(string destination) // From ITransportation
{
Console.WriteLine("Going to " + destination);
}
}
What you're saying here, is that my class Boat will do everything ITransportation has told me too.
And then when you want to make software for a transport company. You could have a method
Void ProvideServiceForClient(ITransportation transportationMethod, string whereTheyWantToGo)
{
transportationMethod.TakeMeThere(whereTheyWantToGo); // Cause ITransportation has this method
}
So it doesn't matter which type of transportation they want, because we know it can TakeMeThere
This is not specific to C#,so i recommend to move to some othere flag.
for your question,
the main reason why we opt for interface is to provide a protocol between two components(can be a dll,jar or any othere component).
Please refer below
public class TestClass
{
static void Main()
{
IMyInterface ob1, obj2;
ob1 = getIMyInterfaceObj();
obj2 = getIMyInterfaceObj();
Console.WriteLine(ob1.CallSomeMethod());
Console.WriteLine(obj2.CallSomeMethod());
Console.ReadLine();
}
private static bool isfirstTime = true;
private static IMyInterface getIMyInterfaceObj()
{
if (isfirstTime)
{
isfirstTime = false;
return new ImplementingClass1();
}
else
{
return new ImplementingClass2();
}
}
}
public class ImplementingClass1 : IMyInterface
{
public ImplementingClass1()
{
}
#region IMyInterface Members
public bool CallSomeMethod()
{
return true;
}
#endregion
}
public class ImplementingClass2 : IMyInterface
{
public ImplementingClass2()
{
}
#region IMyInterface Members
public bool CallSomeMethod()
{
return false;
}
#endregion
}
public interface IMyInterface
{
bool CallSomeMethod();
}
Here the main method does not know about the classes still it is able to get different behaviour using the interface.
The purpose of the Interface is to define a contract between several objects, independent of specific implementation.
So you would usually use it when you have an Intrace ISomething, and a specific implementation
class Something : ISomething
So the Interface varialbe would come to use when you instantiate a contract:
ISomething myObj = new Something();
myObj.SomeFunc();
You should also read interface C#
Update:
I will explaing the logic of using an Interface for the variable and not the class itself by a (real life) example:
I have a generic repositor interace:
Interface IRepository {
void Create();
void Update();
}
And i have 2 seperate implementations:
class RepositoryFile : interface IRepository {}
class RepositoryDB : interface IRepository {}
Each class has an entirely different internal implementation.
Now i have another object, a Logger, that uses an already instansiated repository to do his writing. This object, doesn't care how the Repository is implemented, so he just implements:
void WriteLog(string Log, IRepository oRep);
BTW, this can also be implemented by using standard classes inheritance. But the difference between using interfaces and classes inheritance is another discussion.
For a slightly more details discussion on the difference between abstract classes and interfaces see here.
Say, for example, you have two classes: Book and Newspaper. You can read each of these, but it wouldn't really make sense for these two to inherit from a common superclass. So they will both implement the IReadable interface:
public interface IReadable
{
public void Read();
}
Now say you're writing an application that will read books and newspapers for the user. The user can select a book or newspaper from a list, and that item will be read to the user.
The method in your application that reads to the user will take this Book or Newspaper as a parameter. This might look like this in code:
public static void ReadItem(IReadable item)
{
item.Read();
}
Since the parameter is an IReadable, we know that the object has the method Read(), thus we call it to read it to the user. It doesn't matter whether this is a Book, Newspaper, or anything else that implements IReadable. The individual classes implement exactly how each item will be read by implementing the Read() method, since it will most likely be different for the different classes.
Book's Read() might look like this:
public void Read()
{
this.Open();
this.TurnToPage(1);
while(!this.AtLastPage)
{
ReadText(this.CurrentPage.Text);
this.TurnPage();
}
this.Close();
}
Newspaper's Read() would likely be a little different:
public void Read()
{
while(!this.OnBackPage)
{
foreach(Article article in this.CurrentPage.Articles)
{
ReadText(article.Text);
}
}
}
The point is that the object contained by a variable that is an interface type is guaranteed to have a specific set of methods on it, even if the possible classes of the object are not related in any other way. This allows you to write code that will apply to a variety of classes that have common operations that can be performed on them.
No, it is not possible. Designers did not provide a way. Of course, it is of common sense also. Because interface contains only abstract methods and as abstract methods do not have a body (of implementation code), we cannot create an object..
Suppose even if it is permitted, what is the use. Calling the abstract method with object does not yield any purpose as no output. No functionality to abstract methods.
Then, what is the use of interfaces in Java design and coding. They can be used as prototypes from which you can develop new classes easily. They work like templates for other classes that implement interface just like a blue print to construct a building.
I believe everyone is answering the polymorphic reason for using an interface and David Hall touches on partially why you would reference it as an interface instead of the actual object name. Of course, being limited to the interface members etc is helpful but the another answer is dependency injection / instantiation.
When you engineer your application it is typically cleaner, easier to manage, and more flexible if you do so utilizing dependency injection. It feels backwards at first if you've never done it but when you start backtracking you'll wish you had.
Dependency injection normally works by allowing a class to instantiate and control the dependencies and you just rely on the interface of the object you need.
Example:
Layer the application first. Tier 1 logic, tier 2 interface, tier 3 dependency injection. (Everyone has their own way, this is just for show).
In the logic layer you reference the interfaces and dependency layer and then finally you create logic based on only the interfaces of foreign objects.
Here we go:
public IEmployee GetEmployee(string id)
{
IEmployee emp = di.GetInstance<List<IEmployee>>().Where(e => e.Id == id).FirstOrDefault();
emp?.LastAccessTimeStamp = DateTime.Now;
return emp;
}
Notice above how we use di.GetInstance to get an object from our dependency. Our code in that tier will never know or care about the Employee object. In fact if it changes in other code it will never affect us here. If the interface of IEmployee changes then we may need to make code changes.
The point is, IEmployee emp = never really knows what the actual object is but does know the interface and how to work with it. With that in mind, this is when you want to use an interface as opposed to an object becase we never know or have access to the object.
This is summarized.. Hopefully it helps.
This is a fundamental concept in object-oriented programming -- polymorphism. (wikipedia)
The short answer is that by using the interface in Class A, you can give Class A any implementation of IMyInterface.
This is also a form of loose coupling (wikipedia) -- where you have many classes, but they do not rely explicitly on one another -- only on an abstract notion of the set of properties and methods that they provide (the interface).

Categories

Resources