Let me give you a brief description about common scenario, let’s say you have two interfaces Interface1, Interface2, and both interfaces are having a method addNumber() with the same signature. Now let’s say you have to implement both interfaces in one class (e.g. Class1: Interface1, Interface2). The question is how the implementation will happen, when you implement the method addNumber in class1, then how run time will come to know which Interface method will be invoked.
Or let’s say you want to provide different implementation of the same method defined in two different interfaces, what will happen.
Now I think the scenario is pretty much clear, this scenario is called Interface name conflict or Interface Collisions. Let’s see how we can handle this problem. You can download the sample code which demonstrates the solution of this problem "Interface name conflict" from this link Sample - C# Interface Collision
Below is the sample code which demonstrate the problem:
Interface Definition:
interface Interface1
{
int addNumber(int x, int y);
}
interface Interface2
Class that implements both interfaces:
public class Class1 : Interface1, Interface2
public int addNumber(int x, int y)
return x + y;
As you can see in the above class the method addNumber is implemented in Class1, the method belongs to both interfaces. The problem comes into the picture when you have to provide different implementation of the same method in the same class.
Below sample code demonstrate how you can provide explicit implementation of both interfaces:
int Interface1.addNumber(int x, int y)
int Interface2.addNumber(int x, int y)
return x + y+2;
To call both methods implemented in class1, you have to type cast the class1 object into either Interface1 or Interface2, then the respective method call will happen. Below sample code demonstrate the same
static void Main(string[] args)
Class1 obj = new Class1();
int x = ((Interface1)obj).addNumber(1, 1);
int y = ((Interface2)obj).addNumber(1, 1);
Console.Write("Value of X: {0} and Value of Y: {1} ", x, y);
Console.Read();
Naomi N edited Revision 6. Comment: Minor edit
Mohammad Nizamuddin edited Revision 4. Comment: format
Mohammad Nizamuddin edited Revision 2. Comment: added link
Mohammad Nizamuddin edited Original. Comment: made correction
You can also combine both techniques.This makes sense if one of the interface implementations shall be used as a default implementation:
Provide (a) one method which implicitly implements the interface and (b) another method which explicitly implements one of the two interfaces.
Method (a) can be used as a "default" without the need to cast a class instance to an interface.
See also this MSDN library article - especially the last section "Code Discussion": msdn.microsoft.com/.../aa288461(v=vs.71).aspx
Carsten, I think you may add this into the article with more information. Nice article!
Agree with Carsten and Naomi, @ Carsten lets add your point in the article