Diamond Problem :
The Diamond problem is related to object oriented languages that allow multiple inheritance.As we know C# does not support multiple inheritance of classes, but it does support multiple inheritance through interfaces. Therefore, the same ambiguity may arise unless explicit interface implementation is used. Going explicitly, we can have different implementations to the same method. The problem is solved.
namespace MulipleInheritance
{
public interface IntBC
{
void Display();
}
public interface IntA : IntBC
{
new void Display();
}
public interface IntB : IntBC
{
new void Display();
}
// C class implements the IntA and IntB interfaces
public class C : IntA, IntB
{
// explicitly implement the Display() method of the IntA interface
void IntA.Display()
{
Console.WriteLine("IntA implementation of Display()");
}
// implement the Display() method of the IntB interface
public void Display()
{
Console.WriteLine("IntB implementation of Display()");
}
}
public class MainClass
{
public static void Main()
{
C ObjC = new C();
Console.WriteLine("Calling ObjC.Display()");
ObjC.Display();
// cast ObjC to IntB
IntA RefIntA = ObjC as IntA;
Console.WriteLine("Calling RefIntA.Display()");
RefIntA.Display();
// cast ObjC to IntA
IntB RefIntB = ObjC as IntB;
Console.WriteLine("Calling RefIntB.Display()");
RefIntB.Display();
}
}
}
Output :
Calling ObjC.Display()
IntB implementation of Display()
Calling RefIntA.Display()
IntA implementation of Display()
Calling RefIntB.Display()
IntB implementation of Display()
In Class C, first Display() method is explicitly implemented for IntA Interface. Explicit implementation is not needed for the second Display() method, because previous statement already did that and the method implementation is automatically assumed to IntB interface. In order to call explicit implementation method casting is required.
No comments:
Post a Comment