Inheriting the same method from multiple interfaces

What we know is that multiple (interface) inheritance is allowed in C #, but I want to know if two interfaces are possible Example:

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

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

will inherit in the class above?

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 so, which interface method will be called.

Thanks in advance.

+4
source share
1 answer

You cannot overload such a method, no - they have the same signature. Your options:

  • Use one implementation that will be called by both interfaces
  • Use an explicit interface implementation for one or both methods, for example

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

    , Calculation; , . :

    public void ShowBoth()
    {
        Console.WriteLine(((calc1)this).addsub(5, 3)); // 8
        Console.WriteLine(((calc2)this).addsub(5, 3)); // 2
    }
    
+10

Source: https://habr.com/ru/post/1607758/


All Articles