I’m currently reading Jon Skeet’s C# in depth 2nd edition and the following question came to my mind:
How’s the compiler able to choose between list.Sort(Comparison<T>) and list.Sort(MyComparison<T>) in the following example:
// MyComparison has the same signature as Comparison<in T>
public delegate int MyComparison<in T>(T x, T y);
public class MyList<T> : List<T>
{
// Sort is like Sort(Comparison<T>) except it takes a MyComparison<T> in parameter
public int Sort(MyComparison<T> comparison)
{
Console.WriteLine("Sort MyComparison<T>");
return -1;
}
}
MyList<Product> list = new MyList<Product>();
list.Sort((product1, product2) => product1.Name.CompareTo(product2.Name));
// Equivalent to
list.Sort(new MyComparison<Product>((product1, product2) => product1.Name.CompareTo(product2.Name)));
// But not equivalent to...
list.Sort(new Comparison<Product>((product1, product2) => product1.Name.CompareTo(product2.Name)));
Thanks in advance
If overload resolution comes across an applicable method, it will use that one in preference to any methods declared in base classes. So in this case, it’s as if
List<T>.Sortdidn’t even exist, for the first two invocations.The third invocation isn’t applicable, so it will find
List<T>.Sortinstead.If you declared another overload for
SortwithinMyList(but takingComparison<T>instead ofMyComparison<T>) then the method call would be ambiguous.See my overload resolution article for more details.
PS Hope you’re enjoying the book 🙂