Why is the generic method called when both overloads would match?
public static void method1(object obj)
{
Console.WriteLine(\"Object\");
}
public stati
To find the matching signature of a method for a call, the compiler search in the type hierarchy from bottom to top as well in virtual table:
Because classes prevail on interfaces.
Indeed, before being of type of an interface, an object is of type of a class first of all.
And non generic signatures prevail over generic as reality and facts prevail over abstraction, unless using the generic parameter allow a call on the more specialized type of instance.
This call:
method1("xyz");
Match perfectly with:
void method1(T t) { }
Before matching with:
void method1(object obj)
Because string is a specialized object and it can be used as a generic parameter to be more acurate.
On the other side, if you write:
void method1(string obj) { }
void method1(T t) { }
The first method is so called.
var instance = new List();
MyMethod(instance);
MyMethod((IEnumerable) instance);
MyMethod(instance);
MyMethod((object)instance);
void MyMethod(List instance) { }
void MyMethod(IEnumerable list) { }
void MyMethod(T instance) { }
void MyMethod(object instance) { }
The first call calls the first method because instance is type of List (type matching).
The second call calls the second method because of the side cast (implementation).
The third call calls the third method because of the generic parameter specified to act on (templating).
The fourth call calls the fourth method because of the down cast (polymorphism).