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"
}
}
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With