Zach <di***********@gmail.comwrote:
Consider the following code:
void Test(int i)
{
System.Console.WriteLine("int function");
}
void Test(object o)
{
System.Console.WriteLine("object function");
}
void Generic<T>(T t)
{
Test(t);
}
If I execute the code
Generic<int>(5);
then "object function" is printed to the screen. I understand why, it
appears to treat generic types as first-class types and decides that
there must exist a compile-time conversion from EVERY legal value for
T (everything in this case, since there is no where clause) to the
overload.
In particular, overloading is always performed at compile time, and the
void Generic<T>(T t) is *not* recompiled (in terms of IL) for the
Generic<int>(5); call. (It will be JIT-compiled separately, but that's
a different matter.)
My questions are:
1) is this theoretically necessary
Well, anything can be done in theory, but this behaviour is consistent
with the general principle of overloading being done at compile-time
and overriding being done at runtime within .NET.
2) What would be the implications of changing this so that the either
the correct overload is selected at runtime rather than at compile
time, or making it so that semantic checking on the code inside
Generic<T>() is done for individual values of T that the function is
instantiated with, and not for the "generic value T"?
Selecting it at runtime would either require using reflection within
the compiled code, or changing the CLR to support overloading at
runtime.
The idea of the Generic<T>() code being checked for individual values
of T doesn't fly: you don't know all the values of T that will be used
when Generic<Tis compiled. This is where .NET generics are
significantly different from C++ templates, which are sort of (very)
glorified macros.
--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog:
http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too