Consider the code:
class ChildClass : BaseClass {
public void Method1() {} //some other method
}
abstract class BaseClass : IChildInterface {
public
virtual //<- If we add virtual so that this method can be overridden by ChildClass, we get StackOverflowException and DoWork() implementation in IChildInterface is never called.
void DoWork() {
//base class specific implmentation
((IChildInterface)this).DoWork(); //call into default implementation provided by IChildInterface
}
}
interface IChildInterface : IBaseInterface {
void IBaseInterface.DoWork() {
//implmentation
}
}
interface IBaseInterface {
void DoWork();
}
The problem is that if we mark DoWork()
in BaseClass
as virtual
so that it can be overridden by child classes, it prevents it from calling into IChildInterface
's default implementation of DoWork()
, causing StackOverflowException
.
If we remove virtual
modifier from DoWork()
in the BaseClass
, everything works and the IChildInterface
's default implementation of DoWork()
is called.
Is such a behavior a bug, or by design?
Is there a way to make it possible for some child classes provide their own implementation of DoWork()
(thus overriding BaseClass
's implementation) but still being able to use IChildInterface
's default implementation of DoWork()
?
void IBaseInterface.DoWork() {
from IChildInterface and add it to ChildClass also you could of made it an abstract method. – Rickertvirtual
modifier anyway. – Whitefly