Wednesday, August 17, 2011

Inheritance from multiple interface with the same method name in C#

Posted by Rahul Kharde at 4:37 AM

Hello Friends,

This article gives an idea about the situation called interface clash. This situation occurs when two interfaces have functions with the same name and signature and one base class implements these interfaces.

When two interfaces have functions with the same name and a class implements these interfaces, then we have to specifically handle this situation. We have to tell the compiler which class function we want to implement. For such cases, we have to use the name of the interface during function implementation.
Have a look at the following example:

CLASS


public class MyClass : IMyInterface1, IMyInterface2
{
    string IMyInterface1.DoSomething()
    {
        return "IMyInterface1";
    }

    string IMyInterface2.DoSomething()
    {
        return "IMyInterface2";
    }

    public string DoSomething()
    {
        return "MyClass";
    }
}

CODE C#:

MyClass ObjMyclass = new MyClass();
//implicit implementation
Console.Write("" + ObjMyclass.DoSomething());
// explicit implementation
// this method will be called if you have a reference to an IMyInterface1 and IMyInterface2
Console.Write("" + +((IMyInterface1)ObjMyclass).DoSomething());
Console.Write(""+ ((IMyInterface2)ObjMyclass).DoSomething());

OUTPUT

MyClass
IMyInterface1
IMyInterface2


If you enjoyed this post and wish to be informed whenever a new post is published, then make sure you subscribe to my regular Email Updates. Subscribe Now!


Kindly Bookmark and Share it:

YOUR ADSENSE CODE GOES HERE

0 comments:

Have any question? Feel Free To Post Below:

 

Popular Posts

Recent Comments

© 2011. All Rights Reserved | Help to understand .Net | Template by Blogger Widgets

Home | About | Top