Home > OS >  Multiple Interface Inheritance with method body
Multiple Interface Inheritance with method body

Time:09-27

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.

CodePudding user response:

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

CodePudding user response:

Your Math class needs some small adaptions to function like you want.

    public class Math : IMath1,IMath2
    {
        int x = 5;
        int y= 6;
        private int z;
        private bool oneOrTwo = true; //True = 1, False = 2
        
        public Math(bool oneOrTwo)
        {
            this.oneOrTwo = oneOrTwo;
            z = GetSum(x, y);
        }

        public int GetSum(int x, int y)
        {
            return oneOrTwo ? ((IMath2)this).GetSum(x, y) : ((IMath1)this).GetSum(x, y);
        }
    }

With the Boolean I decide from witch interface the GetSum should be used and I give z it's value in the constructor, otherwise the GetSum method would need to be static.

And you need to cast this to the interface, otherwise it doesn't know that it has these methods.

If you need to implement the methods in your class, then do this.

public int GetSum(int x, int y)
        {
            return oneOrTwo ? ((IMath1)this).GetSum(x, y) : ((IMath2)this).GetSum(x, y);
        }

        int IMath1.GetSum(int x, int y)
        {
            return x   y;
        }

        int IMath2.GetSum(int x, int y)
        {
            return x * y;
        }
  • Related