Labels

Monday, March 9, 2009

Multi -Inheritance Myth

Hi,

 

We know that C# support mulitiple inheritance using Interfaces. Now if both interface defines a mehhod with the same name then the class implementing these interfaces has to implement atleast one of them with the ‘Explicit Approach’.

 

Using the ‘Explicit Approach’ will hide the call to the implemented method from the derived class, as the implementation of the interface method in derived class is ‘Private’.

i.e the below call cannot make the call to interfaceB method.

 

MyClass obj = new MyClass();

MessageBox.Show(obj.GetMessage());  // InterfaceA

 

However you have to go for another approach as below.

 

InterfaceB b = new MyClass();

MessageBox.Show(b.GetMessage());  // InterfaceB

 

interface InterfaceA

{

  string GetMessage();

}

interface InterfaceB

{

  string GetMessage();

}

 

 

class MyClass : InterfaceA,InterfaceB

    {       

        public string GetMessage() // Implicit

        {

            return "InterfaceA";

        }

 

        string InterfaceB.GetMessage() // Explicit / Private

        {

            return "InterfaceB";

        }

    }

 

 

 

Regards,

Arun Manglick

No comments:

Post a Comment