This question already has answers here:
C# Interfaces. Implicit implementation versus Explicit implementation
(13 answers)
Closed 7 years ago.
What's the difference between Explicitly implement the interface and Implement the interface.
When you derive a class from an interface, intellisense suggest you to do both.
But, what's the difference?
Another aspect of this:
If you implicitly implemented, it means that the interface members are accessible to users of your class without them having to cast it.
If it's explicitly implemented, clients will have to cast your class to the interface before being able to access the members.
Here's an example of an explicit implementation:
interface Animal
{
void EatRoots();
void EatLeaves();
}
interface Animal2
{
void Sleep();
}
class Wombat : Animal, Animal2
{
// Implicit implementation of Animal2
public void Sleep()
{
}
// Explicit implementation of Animal
void Animal.EatRoots()
{
}
void Animal.EatLeaves()
{
}
}
Your client code
Wombat w = new Wombat();
w.Sleep();
w.EatRoots(); // This will cause a compiler error because it's explicitly implemented
((Animal)w).EatRoots(); // This will compile
The IDE gives you the option to do either - it would be unusual to do both. With explicit implementation, the members are not on the (primary) public API; this is handy if the interface isn't directly tied to the intent of the object. For example, the ICustomTypeDescriptor members aren't all that helpful to regular callers - only to some very specific code, so there is no purpose having them on the public API causing mess.
This is also useful if:
there is a conflict between an interface's Foo method and your own type's Foo method, and they mean different things
there is a signature conflict between other interfaces
The typical example of the last point is IEnumerable<T>, which has a GetEnumerator() method at two levels in the interface hierarchy - it is common to implement the typed (IEnumerator<T>) version using implicit implementation, and the untyped (IEnumerator) version using explicit implementation.
Here's the difference in plain English:
Suppose you have an interface Machine, which has a function Run(), and another interface Animal which also has a function called Run(). Of course, when a machine runs, we're talking about it starting up, but when an animal runs, we're talking about it moving around. So what happens when you have an object, lets call it Aibo that is both a Machine and an Animal? (Aibo is a mechanical dog, by the way.) When Aibo runs, does he start up, or does move around? Explicitly implementing an interface lets you make that distinction:
interface Animal
{
void Run();
}
interface Machine
{
void Run();
}
class Aibo : Animal, Machine
{
void Animal.Run()
{
System.Console.WriteLine("Aibo goes for a run.");
}
void Machine.Run()
{
System.Console.WriteLine("Aibo starting up.");
}
}
class Program
{
static void Main(string[] args)
{
Aibo a = new Aibo();
((Machine)a).Run();
((Animal)a).Run();
}
}
The catch here is that I can't simply call a.Run() because both of my implementations of the function are explicitly attached to an interface. That makes sense, because otherwise how would the complier know which one to call? Instead, if I want to call the Run() function on my Aibo directly, I'll have to also implement that function without an explicit interface.
Explicit will put IInterfaceName. at the front of all of the interface implementations. It's useful if you need to implement two interfaces that contain names/signatures that clash.
More info here.
Explicitly implement puts the fully qualified name on the function name consider this code
public interface IamSam
{
int foo();
void bar();
}
public class SamExplicit : IamSam
{
#region IamSam Members
int IamSam.foo()
{
return 0;
}
void IamSam.bar()
{
}
string foo()
{
return "";
}
#endregion
}
public class Sam : IamSam
{
#region IamSam Members
public int foo()
{
return 0;
}
public void bar()
{
}
#endregion
}
IamSam var1;
var1.foo() returns an int.
SamExplicit var2;
var2.foo() returns a string.
(var2 as IamSam).foo() returns an int.
Here you go, directly from MSDN
The difference is that you can inherit a class from several interfaces. These interfaces may have identical Method signatures. An explicit implementation allows you to change your implementation according to which Interface was used to call it.
Explicit interface implementation, where the implementation is hidden unless you explicitly cast, is most useful when the interface is orthogonal to the class functionality. That is to say, behaviorally unrelated .
For example, if your class is Person and the interface is ISerializable, it doesn't make much sense for someone dealing with Person attributes to see something weird called 'GetObjectData' via Intellisense. You might therefore want to explicitly implement the interface.
On the other hand, if your person class happens to implement IAddress, it makes perfect sense to see members like AddressLine1, ZipCode etc on the Person instances directly (implicit implementation).
Related
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)
I defined a generic method Use<T> in an interface IInterface. I tried to make an implementation of that interface where the concrete implementation of the Use<T> method depends on the actual type T, and I want to always call the most specialized method. But it does not work:
interface IInterface { void Use<T>(T other) where T : IInterface; }
interface IChildInterface : IInterface { }
class ImplementsIInterface : IInterface
{
public void Use<T>(T other) where T : IInterface
{
Debug.WriteLine("ImplementsInterface.Use(IInterface)");
}
}
class ImplementsChildInterface : IChildInterface
{
public void Use<T>(IChildInterface other) where T : IInterface
{ // idea: if other is IChildInterface, use this method
Debug.WriteLine("ImplementsChildInterface.Use(IChildInterface)");
}
public void Use<T>(T other) where T : IInterface
{ // idea: if above method is not applicable, use this method
Debug.WriteLine("ImplementsChildInterface.Use(IInterface)");
}
}
Here is my main method:
public static void Main()
{
IChildInterface childinterf = new ImplementsChildInterface();
childinterf.Use(new ImplementsChildInterface()); // outputs "ImplementsChildInterface.Use(IInterface)"
// but should output "ImplementsChildInterface.Use(IChildInterface)"
childinterf.Use(new ImplementsIInterface()); // outputs "ImplementsChildInterface.Use(IInterface)"
}
The method that takes an IChildInterface argument is never called, although it should.
Is there a way to make this work? Or is my approach fundamentally wrong?
Note that it is a necessity that IInterface only has one method definition. I might enlarge the interface hierarchy at any time (and thus increase the number of implementations I could provide in an implementing class), but this should not lead to needing to add more method definitions in IInterface. Otherwise, the whole point of using interfaces (i.e. to be flexible) would be missed.
The answers I got so far all involve the need to cast. This is also something I don't want to do, since it makes the whole setup useless. Let me explain the broader picture of what I try to achieve:
Let's imagine we created some instance of an IInterface (like so: IInterface foo = new ImplementsChildInterface();). It will behave in a certain way, but it will always behave in the same way - no matter if we see it as an IInterface, an IChildInterface or an ImplementsChildInterface. Because, if we call some method on it, the compiler (or runtime? i don't know) will check what type it REALLY is and run the method defined in that type.
Now imagine we have two instances i1 and i2 of IInterface. They again are, under the hood, concrete implementations of IInterface, so they have a concrete behaviour, no matter through which glasses we seem them.
So when I run i1.Use(i2), the compiler (or runtime?) should be able to find out what i1 and i2 REALLY are, and run the corresponding method. Like so:
Which type does i1 have? ImplementsChildInterface, ok, then I'll look at the methods there.
Which type does i2 have? ImplementsIInterface, ok, then let's see if there exists a method Use(ImplementsIInterface ...). There is none, but maybe there is a fallback? ImplementsIInterface is a IInterface, so let's see if there exists a method Use(IInterface ...). Yes, it exists, so let's call it!
Neither IInterface nor IChildInterface have a member Use<T>(IChildInterface other) defined, but only Use<T>(T other).
Your class ImplementsChildInterface on the other side has a method Use<T>(IChildInterface other). As you declaring childInterf as a reference of type IChildInterface you can´t access that member, but unly those defined in the interface. So you should cast to the actual class in order to access the method accepting an instance of IChildInterface. But even then the generic implementation is used. So you should also cast your parameter to IchildInterface:
ImplementsChildInterfacechildinterf = new ImplementsChildInterface();
childinterf.Use(((IChildInterface)new ImplementsChildInterface());
childinterf.Use(new ImplementsIInterface());
Furthermore as you don´t use the generic type-parameter within your more specialized method, you can also omit it:
class ImplementsChildInterface : IChildInterface
{
public void Use(IChildInterface other)
{ // idea: if other is IChildInterface, use this method
Debug.WriteLine("ImplementsChildInterface.Use(IChildInterface)");
}
public void Use<T>(T other) where T : IInterface
{ // idea: if above method is not applicable, use this method
Debug.WriteLine("ImplementsChildInterface.Use(IInterface)");
}
}
Alternativly you may also add a method into your IChildInterface:
void Use<T>(IChildInterface other) where T : IChildInterface;
Now you can use
IChildInterface childinterf = new ImplementsChildInterface();
childinterf.Use<IChildInterface>(new ImplementsChildInterface()); // outputs "ImplementsChildInterface.Use(IInterface)"
which will print the desired output.
I've struck upon something I don't really understand.
I have a project, where I have an interface that is internal. The class that implements that interface is also internal. In the implementation of the interface, I make all the members that I implement, internal. I did not do an explicit implementation.
I have two interfaces and two classes that implement those interfaces where this works fine.
It would look something like this:
internal interface IA
{
void X();
}
and then
internal class CA : IA
{
internal void X()
{
...
}
}
This works fine for the two aforementioned classes. But when I try to do it with another interface and class, it doesn't work. In fact, for the example above, I get the error:
'WindowsFormsApplication1.CA' does not implement interface member 'WindowsFormsApplication1.IA.X()'. 'WindowsFormsApplication1.CA.X()' cannot implement an interface member because it is not public.
I realize I can make the methods public or do an explicit implementation (and omit the internal and public modifiers), but I'm simply confused as to why it works with the two classes it works with and yet I seem to be unable to replicate it anywhere else.
Butchering the code a bit (because it's confidential), this is one of the ones that actually works in my project.
internal interface IScanner
{
void SetHardware(Hardware hardware);
void Start();
void PauseScan();
void ResumeScan();
void Stop();
bool InScan { get; }
event ScanCompleteHandler ScanComplete;
}
Then I have the class:
internal class MyScanner : IScanner
{
internal void SetHardware(Hardware hardware)
{
...
}
internal void Start()
{
...
}
internal void Stop()
{
...
}
internal void PauseScan()
{
...
}
internal void ResumeScan()
{
...
}
internal bool InScan
{
get
{
...
}
}
internal event ScanCompleteHandler ScanComplete;
}
To make things even stranger, I created another internal class called Temp. I then had it implement the IScanner interface and I copied and pasted the implementation from MyScanner over to it and it won't compile, giving me the error that: "cannot implement an interface member because it is not public."
Can anyone explain this inconsistency?
Thanks
(Updated to fix a typo and clarify some text)
EDIT: Additional Information
I ran the code through reflector and my implementations have been compiled as explicit implementations, even though they aren't explicit. Reflector shows no signs of the internal keywords. All I can guess is that this is some sort of glitch in the compiler that, for some reason, allowed me to make them internal and implicit and that it somehow resolved that as being an explicit implementation.
I've looked over the code a number of times. I can't find any other explanation for it.
If you are implicitly implementing an interface I believe that the member must be declared public. In your example, CA attempts to implicitly implement the X() method but isn't declared public. If you want to keep X() as internal then you should use explicit interface implementation.
void IA.X() { /* stuff */ }
However, I'll also add that making the X() method public wouldn't do any harm anyway as the class is internal so that member is already restricted by that access modifier... That is, it's already effectively internal... So you might as well just make it public!
I know it has been a while since this question was asked, but maybe I can shed some light on it. According to the C# language specification found here the behavior you described should not be possible. Because under 20.4.2 Interface mapping it is said that the implementation is either explicit or mapped to a public non-static member. So either you have some other scenario than the one you are describing here, or you found a bug in your compiler :).
Probably that your "Temp" class is public and IScanner is internal. This is the reason why you get this error. I consider this very annoying since your are forced to implement it explicitly you cannot specify them as abstract or virtual. For the virtual stuff, I was forced to do an implicit internal virtual implementation of the same API and then call the implicit version from the explicit one. Ugly.
If your intention is to hide a certain implementation from outside, you can implement it explicitly like this:
internal class LDialogService : ILDialogService, ILDialogInternalService
{
public async Task<TValue> ShowAsync<TValue>(ILDialogFragment fragment)
{
throw new NotImplementedException();
}
void ILDialogInternalService.SetComponent(LDialog component)
{
throw new NotImplementedException();
}
}
In the above code, I want to expose ShowAsync method to the outside but keep SetComponent inside. Since ILDialogInternalService is internal, no one can call it from outside except through Reflection.
To all my knowledge you cannot implement interface methods internal. As you stated you can implement them explicitly but then someone can still do ((IScanner)myScanner).SetHardware(hw)
Are you 100% sure your MyScanner implementation does not do something like this:
internal class MyScanner : IScanner
{
void IScanner.SetHardware(Hardware hardware) { this.SetHardware(hardware); }
internal void SetHardware(Hardware hardware)
{
...
}
....
}
or this:
internal partial class MyScanner : IScanner
{
internal void SetHardware(Hardware hardware)
{
...
}
}
internal partial class MyScanner
{
void IScanner.SetHardware(Hardware hardware)
{
this.SetHardware(hardware);
}
}
It's OK to have an internal modifier in an Interface declaration however you CAN'T have ANY modifiers INSIDE the interface, in other words, you can't have any modifier for the interface Members. It's simple as that!
Example:
internal interface IA
{
void X(); //OK. It will work
}
internal class CA : IA
{
**internal** void X() // internal modifier is NOT allowed on any Interface members. It doesn't compile. If it works in your project it's because either you DON'T have the void X() method in the Interface or your are inheriting from a wrong interface maybe accidentally
{
...
}
}
An interface declaration may declare zero or more members. The members of an interface must be methods, properties, events, or indexers. An interface cannot contain constants, fields, operators, instance constructors, destructors, or types, nor can an interface contain static members of any kind.
All interface members implicitly have public access. It is a compile-time error for interface member declarations to include any modifiers. In particular, interfaces members cannot be declared with the modifiers abstract, public, protected, internal, private, virtual, override, or static.
Reference:
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/interfaces
In C++, you can do the following:
class base_class
{
public:
virtual void do_something() = 0;
};
class derived_class : public base_class
{
private:
virtual void do_something()
{
std::cout << "do_something() called";
}
};
The derived_class overrides the method do_something() and makes it private. The effect is, that the only way to call this method is like this:
base_class *object = new derived_class();
object->do_something();
If you declare the object as of type derived_class, you can't call the method because it's private:
derived_class *object = new derived_class();
object->do_something();
// --> error C2248: '::derived_class::do_something' : cannot access private member declared in class '::derived_class'
I think this is quite nice, because if you create an abstract class that is used as an interface, you can make sure that nobody accidentally declares a field as the concrete type, but always uses the interface class.
Since in C# / .NET in general, you aren't allowed to narrow the access from public to private when overriding a method, is there a way to achieve a similar effect here?
If you explicitly implement an interface, this will at least encourage people to use the interface type in the declaration.
interface IMyInterface
{
void MyMethod();
}
class MyImplementation : IMyInterface
{
void IMyInterface.MyMethod()
{
}
}
One will only see MyMethod after casting the instance to IMyInterface. If the declaration uses the interface type, there is no casting needed in subsequent uses.
MSDN page on explicit interface implementation (thanks Luke, saves me a few seconds^^)
IMyInterface instance = new MyImplementation();
instance.MyMethod();
MyImplementation instance2 = new MyImplementation();
instance2.MyMethod(); // Won't compile with an explicit implementation
((IMyInterface)instance2).MyMethod();
You can do this in the .Net world too, using explicit interface implementation
As an example, BindingList<T> implements IBindingList, but you have to cast it to IBindingList to see the method.
You are able to decrease a method's availability by marking it as new.
The example from MSDN's CA2222: Do not decrease inherited member visibility:
using System;
namespace UsageLibrary
{
public class ABaseType
{
public void BasePublicMethod(int argument1) {}
}
public class ADerivedType:ABaseType
{
// Violates rule: DoNotDecreaseInheritedMemberVisibility.
// The compiler returns an error if this is overridden instead of new.
private new void BasePublicMethod(int argument1){}
}
}
This is really more interesting as an academic exercise; if your code is truly dependent on not being able to call BasePublicMethod on ADerivedType, that's a warning sign of a dubious design.
The problem with this strategy, should it be implemented, is that the method is not truly private. If you were to upcast a reference to base_class, then the method is now public. Since it's a virtual method, user code will execute derived_class::do_something() eventhough it's marked as private.
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).