What are the rules regarding function Overloading?
I have the following code:
public T genericFunc<T>() where T : Component, new()
{
T result = new T();
overloadedFunction( result );
}
private overloadedFunction ( Component c ) // catch all function
private overloadedFunction ( DerivedFromComponent dfc) // specific function
when I call the above code with:
genericFunc<DerivedFromComponent>();
I expect the more specific overloadedFunction to be called, however the catch all function is called instead, why is this?. When stepping through the above code the type T is indeed DerivedFromComponent, I thought that the CLR picked the best possible match at runtime!
The compiler performs overload resolution within
genericFuncwhen that method is compiled. At that point it doesn’t know what type argument you’re going to provide, so it only knows that it can call the first of your overloads.Your example using generics makes life more complicated, but overloads are always resolved at compile-time (assuming you’re not using
dynamic).A simple example not using generics:
would call the second overload, because the compile-time type of
xis just object.For more on this, read my recent article on overloading.