Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two interfaces have same method

Tags:

c#

.net

Interface A
{
    int Add(int a,int b);
}

Interface B
{
    int Add(int a,int b);
}

Class D : A, B
{
    int Add(int a,int b)
    {
        return a+b;
    }
}

Code works fine and didn't produce any error. Class D is using which interface's method?

like image 758
user3442500 Avatar asked Aug 22 '26 17:08

user3442500


2 Answers

Neither, since neither interface HAS a method, merely a method signature. Your method in D implements the signature provided by both interfaces, so it works.

Remember, an interface merely specifies the signatures of methods that must exist in an implementation.

like image 198
billjamesdev Avatar answered Aug 25 '26 08:08

billjamesdev


Since method signatures are the same on both interfaces, and class D implements those methods (with a single function), then it doesn't really matter which interface that function implements, and thus compiler is happy.

However, you can have two different implementations specific for each interface by declaring functions as

class D : A, B
{
    int A.Add(int a, int b)
    {
    }

    int B.Add(int a, int b)
    {
    }
}
like image 22
LB2 Avatar answered Aug 25 '26 07:08

LB2



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!