I\'m trying to refresh my memory but can\'t find answers with Google.
public class BaseClass
{
public virtual void DoSomething()
{
Trace.Writ
The solutions with new
instead of override
break the polymorphism. Recently I came to the same problem and implemented it the following way. My solution has the following advantages:
virtual
and override
stays in place;BaseClass
is not used directly in the type cast, so if I introduce an intermediate MiddleClass
in the hierarchy between BaseClass
and DerivedClass
, which also implements DoSomething()
; then the MiddleClass
's implementation won't be skipped.This is the implementation:
public class BaseClass
{
public virtual void DoSomething()
{
Trace.Write("base class");
}
}
public class DerivedClass : BaseClass
{
public override void DoSomething()
{
Trace.Write("derived class");
}
public void BaseDoSomething()
{
base.DoSomething();
}
}
The usage is:
DerivedClass dc = new DerivedClass();
dc.DoSomething();
dc.BaseDoSomething();