Why does the compiler give an ambiguous invocation error when passing inherited types?
Posted
by
Matt Mitchell
on Stack Overflow
See other posts from Stack Overflow
or by Matt Mitchell
Published on 2013-10-25T03:49:13Z
Indexed on
2013/10/25
3:53 UTC
Read the original article
Hit count: 145
c#
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
}
© Stack Overflow or respective owner