Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheriting the same method from multiple interfaces

Tags:

c#

inheritance

That we know multiple (interface) inheritance is allow in c# but, I want to know is it possible that two interface Example :

 interface calc1
{
    int addsub(int a, int b);
}
interface calc2
{
    int addsub(int x, int y);
}

with same method name with same type and with same type of parameter

will get inherit in above class ?

class Calculation : calc1, calc2
{
    public int result1;
    public int addsub(int a, int b)
    {
        return result1 = a + b;
    }
    public int result2;
    public int addsub(int x, int y)
    {
        return result2= a - b;
    }
}

if yes then which interface method will get called.

Thanks in advance.

like image 222
Liquid Avatar asked Dec 25 '22 14:12

Liquid


1 Answers

You can't overload the method like that, no - they have the same signatures. Your options are:

  • Use one implementation, which will be called by both interfaces
  • Use explicit interface implementation for one or both of the methods, e.g.

    int calc2.addsub(int x, int y)
    {
        return result2 = a - b;
    }
    

    If you do that for both methods, neither method will be callable on a reference of type Calculation; instead, you'd have to cast to one interface or the other before calling the method, including within the class. For example:

    public void ShowBoth()
    {
        Console.WriteLine(((calc1)this).addsub(5, 3)); // 8
        Console.WriteLine(((calc2)this).addsub(5, 3)); // 2
    }
    
like image 69
Jon Skeet Avatar answered Dec 28 '22 06:12

Jon Skeet