Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access Interface method implemented in the derived class from child class?

I have two interfaces A,B both has same method declarations. I have a class C inheriting from interfaces A,B. I have another class D inheriting from C. Now i want to access the implemented methods in C from D

interface A
{
    int add(int x, int y);
    int mul(int x, int y);
}

interface B
{
    int add(int x, int y);
    int mul(int x, int y);
}

public class C : A,B
{
    int A.add(int x,int y)
    {
        return x + y;
    }

    int A.mul(int x,int y)
    {
        return 0;
    }

    int B.add(int x, int y)
    {
        return x;
    }

    int B.mul(int x, int y)
    {
        return y;
    }  
}


class D : C
{
}

How to access the methods in C from D?

like image 733
Praveen Avatar asked Oct 21 '25 03:10

Praveen


2 Answers

How to access the methods in C from D?

You have to use a reference with a compile-time of the relevant interface. For example:

class D
{
    public void FooA()
    {
        A a = this;
        Console.WriteLine(a.mul(...));
    }

    public void FooB()
    {
        B b = this;
        Console.WriteLine(b.mul(...));
    }
}

Of course you don't need the local variable - you can cast:

Console.WriteLine(((A) this).mul(...));

... but it gets a bit ugly.

This is just because you're using explicit interface implementation. If you implemented one of the interfaces implicitly, you could just call the methods directly as normal... but explicit interface implementation only allows a member to be called via that interface.

like image 131
Jon Skeet Avatar answered Oct 23 '25 18:10

Jon Skeet


An explicit interface method invocation should always work

((A)this).mul(1,1);
like image 26
Wiktor Zychla Avatar answered Oct 23 '25 17:10

Wiktor Zychla



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!