This is something i assumed was common knowledge, but apparently it isn't.
If you want to have a method in your derived class with the same name as the one in the base class and the base class one isn't marked
as virtual you can use the NEW keyword.
This is also the default behaviour and the compiler treats the child class method as new, however you get a warning for this.
Some code to illustrate this:
public class BaseClass
{
public BaseClass()
{ }
public void IAmANonVirtualMethod()
{
Console.WriteLine("IAmANonVirtualMethod in BaseClass.");
}
public virtual void IAmAVirtualMethod()
{
Console.WriteLine("IAmAVirtualMethod in BaseClass.");
}
}
public class ChildClass : BaseClass
{
public ChildClass()
{ }
public new void IAmANonVirtualMethod()
{
Console.WriteLine("IAmANonVirtualMethod in ChildClass.");
}
}
BaseClass bc = new BaseClass();
ChildClass cc = new ChildClass();
bc.IAmANonVirtualMethod();
cc.IAmANonVirtualMethod();
bc.IAmAVirtualMethod();
cc.IAmAVirtualMethod();
/* Output
IAmANonVirtualMethod in BaseClass.
IAmANonVirtualMethod in ChildClass.
IAmAVirtualMethod in BaseClass.
IAmAVirtualMethod in BaseClass.
*/