Search code examples
c#c#-8.0default-interface-member

Multiple Interface Inheritance with method body


Suppose I have these 2 Interfaces.

public interface IMath2
{
    int GetSum(int x, int y)
    {
        return x + y;
    }
}

public interface IMath1
{
    int GetSum(int x, int y)
    {
        return x + y;
    }
}

and One class with inherit Imath1 and Imath2.

public class Math : IMath1,IMath2
{
    int x = 5, y= 6;
    int z = GetSum(x,y);
}

Here, I can't access the GetSum method from parent Interfaces. Please provide solutions.


Solution

  • Here's a working example:

    void Main()
    {
        var m = new Math();
        m.ExampleGetSum(1, 2);
    }
    
    public interface IMath2
    {
        int GetSum(int x, int y)
        {
            return x + y + 2;
        }
    }
    
    public interface IMath1
    {
        int GetSum(int x, int y)
        {
            return x + y + 1;
        }
    }
    
    public class Math : IMath1, IMath2
    {
    
        public void ExampleGetSum(int x, int y)
        {
            int z1 = (this as IMath1).GetSum(x, y);
            int z2 = (this as IMath2).GetSum(x, y);
    
            Console.WriteLine(z1);
            Console.WriteLine(z2);
        }
    }
    

    That give me this output:

    4
    5