Explicit Interface Implementation
Implementing multiple interfaces can sometimes result in a collision between member signatures. You can resolve such collisions by explicitly implementing an interface member. Consider the following example:
interface I1 { void Foo(); }
interface I2 { int Foo(); }
public class Widget : I1, I2
{
public void Foo()
Console.WriteLine("Widget's implementation of I1.Foo");
}
int I2.Foo()
Console.WriteLine("Widget's implementation of I2.Foo");
return 42;
We can provide the implementation from this way given below
Answer: This is again one those typical .NET Interview questions which move around interfaces to confuse the developer.
For providing different implementation you can qualify the method names with interface names as as shown below. A reference to I1 will display "This is I1" and reference to I2 will display "This is I2". Below is the code snippet for the same.
interface I1 {void MyMethod();} interface I2 { void MyMethod(); } class Sample : I1, I2 { public void I1.MyMethod() { Console.WriteLine("This is I1"); }public void I2.MyMethod() { Console.WriteLine("This is I2"); } }
50 .NET Interview questions and answers