Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When you implement two interfaces with the same method, how do you know which one is called?

Tags:

c#

interface

If you have TheMethod() in interfaces I1 and I2, and the following class

class TheClass : I1, I2
{
    void TheMethod()
}

If something instantiates TheClass, how does it know which interface it is using?

like image 835
user758055 Avatar asked May 17 '11 20:05

user758055


People also ask

What happens when two interfaces have the same method?

However, if two interfaces implement the same default method, then there is a conflict. In cases where one interface inherits another interface and both of them implement a default method, an implementing class would use the default method of the child interface.

CAN 2 interfaces have the same method name?

The implementation of interface's members will be given by the class who implements the interface implicitly or explicitly. C# allows the implementation of multiple interfaces with the same method name.

Can you implement 2 interfaces?

A class can implement more than one interface at a time. A class can extend only one class, but implement many interfaces. An interface can extend another interface, in a similar way as a class can extend another class.

What happens when a class implements two interfaces and both declare field variable with same name?

If both interfaces have a method of exactly the same name and signature, the implementing class can implement both interface methods with a single concrete method.


1 Answers

If that's how the client code is using the class, it doesn't really matter. If it needs to do something interface specific, it should declare the interface it needs, and assign the class to that e.g.

I1 i = new TheClass()
i.TheMethod();

Of course, using your current implementation TheClass, it doesn't matter if declared i as I1, or I2, as you only have a single implementation.

If you want a separate implementation per interface, then you need to create explicit implementations ...

    void I1.TheMethod()
    {
        Console.WriteLine("I1");
    }

    void I2.TheMethod()
    {
        Console.WriteLine("I2");
    }

But keep in mind, explicit implementations cannot be public. You can implement just one explicitly, and leave the other as the default which can be public.

    void I1.TheMethod()
    {
        Console.WriteLine("I1");
    }

    public void TheMethod()
    {
        Console.WriteLine("Default");
    }

Have a look the msdn article for more details.

like image 80
musaul Avatar answered Nov 15 '22 00:11

musaul