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.
It actually makes sense that the generic method is called as it is the most specific of all three.
The interface and the object one are less specific as they both require an upcast while the generic does not.
Moreover : the idea of a generic method is that its behavior is independent of the actual type it is specialized with. In particular, there will be only one specialization generated by the runtime that covers all the reference type cases.