I have the following classes:
public class BaseRepository
public virtual void Delete(int id)
Console.WriteLine("Delete by id in BaseRepository");
public class EFRepository: BaseRepository
public override void Delete(int id)
Console.WriteLine("Delete by Id in EFRepository");
public void Delete(object entity)
Console.WriteLine("Delete by entity in EFRepository");
var repository = new EFRepository();
int id = 1;
Basically, the way method invocation works in C# is that the compiler looks at the most derived class first, and sees whether any newly declared methods (not just overridden ones) are applicable for the arguments for the call. If there's at least one applicable method, overload resolution works out which is the best one. If there isn't, it tries the base class, and so on.
I agree this is surprising - it's an attempt to counter the "brittle base class" issue, but I would personally prefer that any overridden methods were included in the candidate set.
Method invocation is described in section 22.214.171.124 of the C# 5 specification. The relevant parts here is:
- The set of candidate methods is reduced to contain only methods from the most derived types: For each method
C.Fin the set, where
Cis the type in which the method
Fis declared, all methods declared in a base type of
Care removed from the set. Furthermore, if
Cis a class type other than object, all methods declared in an interface type are removed from the set. (This latter rule only has affect when the method group was the result of a member lookup on a type parameter having an effective base class other than object and a non-empty effective interface set.)
And in the member lookup part of 7.4,
override methods are explicitly removed:
Members that include an
overridemodifier are excluded from the set.