Why does the compiler give an ambiguous invocation error when passing inherited types?
- by Matt Mitchell
What is happening in the C# compiler to cause the following ambiguous invocation compilation error?
The same issue applies to extension methods, or when TestClass is generic and using instance rather than static methods.
class Type1 { }
class Type2 : Type1 {}
class TestClass
{
public static void Do<T>(T something, object o) where T : Type1
{}
public static void Do(Type1 something, string o)
{}
}
void Main()
{
var firstInstance = new Type1();
TestClass.Do(firstInstance, new object()); // Calls Do(Type1, obj)
TestClass.Do(firstInstance, "Test"); // Calls Do<T>(T, string)
var secondInstance = new Type2();
TestClass.Do(secondInstance, new object()); // Calls Do(Type1, obj)
TestClass.Do(secondInstance, "Test"); // "The call is ambiguous" compile error
}