You may use the new
keyword to have another definition of the same (named) method. Depending on the type of reference, you call A
's of B
's implementation.
public class A
{
public void F()
{
Console.WriteLine( "A" );
}
}
public class B : A
{
public new void F()
{
Console.WriteLine( "B" );
}
}
static void Main( string[] args )
{
B b = new B();
// write "B"
b.F();
// write "A"
A a = b;
a.F();
}
If you feel that new
is not the right solution, you should consider to write two methods with a distinguished name.
Generally, you can't call the base implementation from outside the class if the method is properly overridden. This is an OO concept. You must have another method. There are four ways (I can think of) to specify this distinguished method:
- write a method with another name.
- write a method with same name but another signature (arguments). It's called overloading.
- write a new definition of the method with the same name (use the
new
keyword) It's called hiding.
- Put it onto interfaces and implement at least one explicitly. (similar to
new
, but based on interface)