c#: Variable types in delegate - c#

I'm trying to break down the problem to a more simple description.
I'm using an external class library, which exposes 4 base classes, all very similar, sometimes derived from each other.
During the execution I'm called back on several delegate functions, all carrying an "object Sender", which contains the initial object of one of the 4 base classes, called on an API function before.
Sample (more or less pseudo code):
classA oA = new classA();
oA.API(callbackA);
Later on the callback is called, carrying oA as "Sender".
void callbackA(object Sender) {
classA oA = (classA)Sender;
oA.API2(xxx);
....
}
The approach above works fine. Now I wanted to extend it to the remaining 3 classes. Because the handling in their callbacks is rather identical, I didn't want to replicate the code another 3 times, but would rather make callbackA ready to deal with Senders of type classB, classC and classD.
I cannot achieve this in any usefull solution. Is anybody able to help me?
UPDATE: Because I did get lot of answer pointing to "is" - "is" is not a solution. I need to have ONE variable, capable of having multiple types. Dynamic casting?

Something like:
void callbackA(object Sender)
{
if (sender is ClassA)
{
classA oA = (classA)Sender;
oA.API2(xxx);
}
else if (sender is ClassB)
{
classB oB = (classB)Sender;
oB.API2(xxx);
}
....
}
It becomes a lot more productive when you can use a common baseclass or interface of A and B.

I'm assuming you aren't using a common interface because the class library is 'external' and you can't access the source. I'm also assuming that all of the possible concrete types for sender expose the same set of properties and methods--as far as your callback method is concerned.
Without a common base or interface you won't be able to avoid reflection or some conditional casting and repeated code. You can, however, encapsulate that code in a wrapper class. That would improve the readability of your callback method.
void callbackA(object sender)
{
var wrappedSender = new MyWrapper(sender);
wrappedSender.API2();
}
Again, assuming all sender classes are treated the same by your callback, you can use System.Reflection in your wrapper class to invoke the appropriate method (or access the appropriate properties). Using API2 as an example:
public class MyWrapper
{
object _wrappedClass;
public MyWrapper(object obj)
{
_wrappedClass = obj;
}
//...
public void API2()
{
MethodInfo api2 = _wrappedClass.GetType().GetMethod("API2");
api2.Invoke(_wrappedClass);
}
//...
}
This doesn't solve your problem exactly but it does separate the reflection 'plumbing' from your callback's intended behavior.

You could have a look at is operator C#
The is operator is used to check
whether the run-time type of an object
is compatible with a given type.
Also, if these classes shared a common interface that would help you greatly.

Using reflection for this is bad style, you should try to create a common interface for those classes and pass this to the delegate. If this is not possible then wrap the classes into wrappers which share an interface, i.e.:
interface IMyDelegate {
public void HandleCallback();
}
class WrapperA : IMyDelegate {
private ClassA classA;
public WrapperA(ClassA classA) {this.classA = classA;}
public void HandleCallback()
{
/* ... your callback code here ... */
}
}
Same for ClassB, ClassC and ClassD.
Then you pass it to the Callback and cast it to the interface:
void callback(object sender) {
IMyDelegate caller = (IMyDelegate)sender;
caller.HandleCallback();
}

Related

C# interface instance-like... help me understand [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Interfaces: Why can't I seem to grasp them?
to work with a library I just found I need to implement a few interfaces first. But some methods seem to be asking for objects that have the type of some interfaces...
And if I have an interface called MyInterface I can write things like :
MyInterface shoe;
It does not really make sense to me. Can somebody teach me this concept ?
I read this : http://www.dotnetperls.com/interface but it did not really help, I think this concept is a bit more complex than what is presented here.
Thanks !
edit :
For those who wonder, I am not new to Interfaces but it is the first time I ran into such a use of them. And for those downgrading my question, I did search but was unlucky apparently.
A simple explanation: A class is like a company. If it claims to be a sales company, it has to provide sales services. It it claims to be a train factory, it has to be able to make trains.
If the national railroads wants to buy trains, it can use any company that can produce trains.
An interface describes what a class has to be able to do. It is like a contract. Each class that wants to have an interface has to fulfill that contract and be able to do what the contract says it has to do. Class instances can perform actions through class methods.
However, the contract doesn't say how the class should do it. So a class can implement the functionality however it wants, or in other words, implement the interface.
public Train
{
private price;
public Train(float price) { this.price = price; }
}
public IMyInterface
{
Train MakeTrain();
}
public ExpensiveTrainFactory : ITrainProducer
{
// make a luxury, expensive train
public Train MakeTrain() { return new Train(4000.0); }
}
public CheapTrainFactory : ITrainProducer
{
// make a cheap train
public Train MakeTrain() { return new Train(500.0); }
}
public NationalRailways
{
List<Train> trains;
public NationalRailways()
{
this.trains = new List<Train>();
}
public Train BuyTrain(ITrainProducer factory)
{
// you can call MakeTrain() because the ITrainProducer guarantees that it can make trains
trains.Add(factory.MakeTrain());
}
}
and then in your code:
NationalRailways railway = new NationalRailways();
ExpensiveTrainFactory expFactory = new ExpensiveTrainFactory();
CheapTrainFactory cheapFactory = new CheapTrainFactory();
// expFactory implements ITrainProducer, so I can use it from BuyTrain(ITrainProducer)
railways.BuyTrain(expFactory);
// cheapFactory implements ITrainProducer, so I can use it from BuyTrain(ITrainProducer) as well
railways.BuyTrain(cheapFactory);
You can declare an Interface, like in your example. However you can not instantiate one.
MyInterface shoe = new MyInterface ();
The above is not legal code. Since an Interface just describes a contract, it has no implementation details, this is left to the client code (you). Therefore it makes no sense to be able to create actual instances of MyInterface.
What you can do, is have a class SomeClass, implement the MyInterface contract:
SomeClass: MyInterface
{
//implement the methods of MyInterface. All of them, to fulfill the contract.
}
Then you can do things like:
MyInterface shoe = new SomeClass();
Since SomeClass implements the MyInterface contract, the above is legal. You can create an instance of SomeClass because it contains implementation details.
Then you can build on this and create more classes which implement MyInterface.
The beauty of this is that you can have a method for example:
void someMethod (MyInterface test)
{
}
You can pass this method the SomeClass object or any other class you created which implements MyInterface.
Then inside this method, you can call methods that the contract contains without knowing the exact object which has been passed to you. This makes writing future code easier. You can create new objects and so long as they implement MyInterface, it is valid to pass this object to someMethod without changing the declaration of the method.
You are correct, you can't directly create an instance of an interface. However, you can create an instance of some type that implements that interface.
Say I have an interface
public IMyInterface
{
void DoSomething();
}
(note: usually you start the name of an interface with "I")
Plus I have a class
public MyClass: IMyInterface
{
public void DoSomething() { ... }
}
Then I can do
IMyInterface something = new MyClass();
although you often call some (factory) method to return some class that implements that interface instead of directly doing a new.
By using the interface as the type of your variable, you specify that you are only interested in the methods and properties specified there.
In C#, each value has two different types: apparent type and actual type. The apparent type is the type of the variable holding the value, and the actual type comes from the constructor used to create the value. Let's say we have the following class:
class MyClass : BaseClass, IMyInterface {
/* ... */
}
Then all the following declarations are valid:
object obj1 = new MyClass();
IMyInterface obj2 = new MyClass();
BaseClass obj3 = new MyClass();
MyClass obj4 = new MyClass();
The apparent and actual types are as follows:
object obj1 = new MyClass(); /* apparent: object, actual: MyClass */
IMyInterface obj2 = new MyClass(); /* apparent: IMyInterface, actual: MyClass */
BaseClass obj3 = new MyClass(); /* apparent: BaseClass, actual: MyClass */
MyClass obj4 = new MyClass(); /* apparent: MyClass, actual: MyClass */
When you manipulate an object (call its methods, etc), you do it assuming the object has its apparent type - you can't call any class-specific methods of an object. The apparent type dictates the interface of the object visible outside the object.
What actually happens under the hood is done according to the object's actual type - for example, if you override the ToString method of your class, the overridden method is called in the following code:
object obj = new MyClass();
Console.WriteLine(obj.ToString());
The actual type dictates how the object's functionality is implemented.
Interfaces establish a contract between a class and the code that calls it. They also allow you to have similar classes that implement the same interface but do different actions or events and not have to know which you are actually working with. This might make more sense as an example so let me use same example as per your link with bit of modification:
using System;
interface IPerl
{
void Read();
}
class Test : IPerl
{
public void Read()
{
Console.WriteLine("Read Test");
}
}
class Test1 : IPerl
{
public void Read()
{
Console.WriteLine("Read Test1");
}
}
class Program
{
static void Main()
{
IPerl perl = new Test(); // Create instance of Test.
perl.Read(); // Call method on interface output will be different then Test1.
perl = new Test1(); // Create instance of Test1.
perl.Read(); // Call method on interface output will be different then Test.
}
}
Output:
"Read Test"
"Read Test1"
I hope this would help.
Thanks Ankur
What Interfaces Are
Interfaces basically define a blueprint for a class or a struct. The programmed definition of an interface looks very similar to a class, but nothing is implemented. Interfaces define the properties, methods, events, and indexers, but the interface does not define the implementation of any of these. It just declares their existence. Interfaces will not actually define any functionality. They just define ways in which interactions with a class takes place.
What Interfaces Are Not
Interfaces should not be confused with inheritance. They are two very different things. Inheritance will define a lot of the implementation and is used for code reuse. Interfaces are merely a definition for how communication with the implementing classes must take place. It is like a written contract. A class "signing" the contract will agree to perform certain specified actions in any way it wishes, but it must perform the specified actions.
When to Use Interfaces
Interfaces allow us to create nice layouts for what a class is going to implement. Because of the guarantee the interface gives us, when many components use the same interface it allows us to easily interchange one component for another which is using the same interface. Dynamic programs begin to form easily from this.
For more information visit this post about Understanding_Interfaces_in_C#

Use explicit interface implementations with a dynamic object

I'm experimenting with explicit implentations of interfaces. This is to strip the intellisense with methods which are not valid in the current context.
Use /practical-applications-of-the-adaptive-interface-pattern-the-fluent-builder-context/ as reference. To prove that they would not be callable, I thought I could use the dynamic keyword, because then at least my code would compile. It does compile, but it does not work as expected. The dynamic variable has access to the class methods, but not the interface methods that are explicit implemented.
public interface IAmInterface
{
void Explicit();
void Implicit();
}
public class Implementation : IAmInterface
{
void IAmInterface.Explicit()
{
}
public void Implicit()
{
}
public static Implementation BeginBuild()
{
return new Implementation();
}
}
And here are the 3 tests to prove my point
[Test]
public void TestWorksAsExpected() //Pass
{
var o = Implementation.BeginBuild();
o.Implicit();
}
[Test]
public void TestDoesNotWorkWithExplicitImplementation() //Fails
{
dynamic o = Implementation.BeginBuild();
o.Explicit();
}
[Test]
public void ButWorksForImplicitImplementation() //Pass
{
dynamic o = Implementation.BeginBuild();
o.Implicit();
}
Would anyone be kind enough to explain the reason for this?
One example where I wanted this functionality was to prove that I couldnt add more than two players in a TennisGame.
dynamic o = TennisGame.BeginBuild().With("Player A").Versus("Player B");
o.Versus("Player C"); //Should fail. It does, but for another reason
The dynamic variable has access to the class methods, but not the interface methods that are explicit implemented.
Yes, that is correct. dynamic has access to the regular members that would be accessible (based on context etc, usually means "public"). However, the only way, even in regular C#, to invoke explicit interface implementations, is to cast the object to the interface. This remains the case with dynamic.
Implicit interfact implementations are also part of the regular class API, so they are externally available (against the type) to both regular c# and dynamic.
Basically: no, dynamic can not and will not access explicit interface implementations.
Either cast to the interface, or use reflection from the interface type (not the object type).

How to access the properties of an instance of a derived class which is passed as a parameter in the form of the base class

In C# I have a base class and a derived class.
I have a function which has the base class as an input parameter
public void SomeFunction(BaseClass InstanceOfDerivedClass)
Is there a way I can access the properties specific to the derived class, even though it has been passed as a base class? Could I use GetType or Cast or something like that?
I appreciate that the solutions may not be elegant but at the moment the alternative is to repeat this function many times for the different derived classes.
Casting should definitely do the trick, since the reference in the heap is to that class. Maybe something like:
if (InstanceOfDerivedClass is DerivedClass)
And in that block you can cast it and interact with it.
But the bigger question is, why do you need to? It sounds like this method is using the wrong abstraction if the type being accepted as an argument isn't the correct type. This is breaking Liskov Substitution and looks like a prime candidate for refactoring the design. (Of which we don't know enough to help much.)
you could do this (bad way):
public void SomeFunction(BaseClass instanceOfDerivedClass)
{
DerivedClass derived = null;
if(instanceOfDerivedClass is DerivedClass)
{
derived = instanceOfDerivedClass as DerivedClass;
// Do stuff like :
int prop = derived.DerivedProperty;
}
}
Or, as suggested by Eric (good way):
public void SomeFunction(BaseClass instanceOfDerivedClass)
{
DerivedClass derived = instanceOfDerivedClass as DerivedClass;
if(derived != null)
{
// Do stuff like :
int prop = derived.DerivedProperty;
}
}

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).

Difference between implicit and explicit implementation of C# interfaces [duplicate]

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).

Categories

Resources