The method executed is not the one I expected even though the type constraint gives the compiler enough information to choose the correct overloaded method signature
Without the generic method it is calling void DoSomething(IInterface obj)
as I expect. With the generic method, void DoSomething<T>(T obj)
is instead being called as it is for some reason considered the better candidate in this case.
interface IInterface
{
void Method();
}
class A : IInterface
{
public void Method()
{
}
}
public class Program
{
static void Gen<T>(T obj) where T : IInterface
{
DoSomething(obj);
}
static void DoSomething<T>(T obj)
{
Console.WriteLine("IN GENERIC DO SOMETHING");
}
static void DoSomething(IInterface obj)
{
Console.WriteLine("IN INTERFACE DOSOMETHING");
}
static void DoSomething(object obj)
{
Console.WriteLine("IN OBJ DO SOMRTHING");
}
public static void Main()
{
IInterface i = new A();
Gen(i);
}
}
I expect the non-generic DoSomething method to be called in all cases as the compiler has a concrete type to work with due to the constraint. Instead, the generic DoSomething is being called. It is only when I remove the generic version that the non-generic method is chosen.