Concept of Method Ambiguity Resolution in C#

Mannan Ul Haq
0
Method ambiguity occurs when a derived class inherits multiple methods with the same name from different interfaces or from a base class and an interface.

Example:

interface IFirstInterface
{
    void SayHello();
}

interface ISecondInterface
{
    void SayHello();
}

class MyClass : IFirstInterface, ISecondInterface
{
    void IFirstInterface.SayHello()
    {
        Console.WriteLine("Hello from the first interface!");
    }

    void ISecondInterface.SayHello()
    {
        Console.WriteLine("Hello from the second interface!");
    }
}

class Program
{
    static void Main()
    {
        MyClass myObject = new MyClass();

        // Let's say hello using the methods from the interfaces
        ((IFirstInterface)myObject).SayHello(); // This will print: Hello from the first interface!
        ((ISecondInterface)myObject).SayHello(); // This will print: Hello from the second interface!
    }
}

In this example, MyClass is using two interfaces: IFirstInterface and ISecondInterface. Both interfaces have a method named SayHello(). To avoid confusion, MyClass specifies which SayHello it's using by telling C# exactly which interface's SayHello() it is implementing. This is called "explicit interface implementation".

Tags

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !