Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I call a base class implementation of an explicitly impemented interface method?

Tags:

c#

I'm trying to call an explicitly implemented interface method implemented on the base class but just can't seem to get it to work. I agree the idea is ugly as hell, but I've tried every combination I can think of, to no avail. In this case, I can change the base class, but thought I'd ask the question to satisfy my general curiosity.

Any ideas?

// example interface
interface MyInterface
{
    bool DoSomething();
}

// BaseClass explicitly implements the interface
public class BaseClass : MyInterface
{
    bool MyInterface.DoSomething()
    {
    }
}

// Derived class 
public class DerivedClass : BaseClass
{
    // Also explicitly implements interface
    bool MyInterface.DoSomething()
    {
        // I wish to call the base class' implementation
        // of DoSomething here
        ((MyInterface)(base as BaseClass)).DoSomething(); // does not work - "base not valid in context"
    }
}
like image 410
cristobalito Avatar asked Sep 28 '11 10:09

cristobalito


1 Answers

You cannot (it is not part of the interface available to subclasses). In that scenario, use something like:

// base class
bool MyInterface.DoSomething()
{
    return DoSomething();
}
protected bool DoSomething() {...}

Then any subclass can call the protected DoSomething(), or (better):

protected virtual bool DoSomething() {...}

Now it can just override rather than re-implement the interface:

public class DerivedClass : BaseClass
{
    protected override bool DoSomething()
    {
        // changed version, perhaps calling base.DoSomething();
    }
}
like image 168
Marc Gravell Avatar answered Sep 25 '22 20:09

Marc Gravell