I have base class A
public class A
{
public virtual void Method(A parameter)
{
Console.WriteLine(MethodBase.GetCurrentMethod());
}
public virtual void Method(B parameter)
{
Console.WriteLine(MethodBase.GetCurrentMethod());
}
}
Inhereted B
public class B : A
{
public virtual void Method(object parameter)
{
Console.WriteLine(MethodBase.GetCurrentMethod());
}
public override void Method(A parameter)
{
Console.WriteLine(MethodBase.GetCurrentMethod());
}
public override void Method(B parameter)
{
Console.WriteLine(MethodBase.GetCurrentMethod());
}
}
Static class S
with extension method
public static class S
{
public static void Method(this B instance, B parameter)
{
Console.WriteLine(MethodBase.GetCurrentMethod());
}
}
Example we create instance of type B
and invoke Method
on it, we expect that it will be public override void Method(B parameter)
actual result is public virtual void Method(object parameter)
.
var b = new B();
b.Method(new B()); // B.Method (Object parameter) Why???
Why compiler doesn't select more suitible method??? UPD And why it is not extension method?
Because it's following the rules of the language specification, where any candidate methods originally declared in a base class (over if they're overridden in a derived class) are ignored when finding a candidate method, unless the derived class doesn't have any applicable methods, at which point the search moves up to the base class, etc.
This is designed to avoid the "brittle base class" problem, but I find that hard to swallow in the face of the method being overridden in the derived class.
The relevant bit of the C# 4 specification is 7.4, which ends with this:
EDIT: About extension methods...
From section 7.6.5.2 of the spec:
So an extension method is only used as a last resort, basically.