SYSK 102: Unexpected Behavior in Generics
Consider the following:
static public class MyClass
{
static public void Method<T>(T x)
{
. . .
MethodX(x);
. . .
}
static private void MethodX(float x)
{
System.Diagnostics.Debug.WriteLine("Float");
}
static private void MethodX(object x)
{
System.Diagnostics.Debug.WriteLine("Object");
}
}
. . .
float x = 1f;
MyClass.Method<float>(x);
. . .
What method will be called – MethodX(float x) or MethodX(object x)?
As it turns out, it’ll always invoke the MethodX(object x)! The only way I found to get the “expected” behavior is to do the explicit cast – MethodX((float) x), which requires the knowledge of passed in data types and an ugly switch statement…
Comments
- Anonymous
April 11, 2006
Yuck, do you know where this is described in the C# spec? - Anonymous
April 11, 2006
No, I don't. If I come across it, I'll add it to the post. - Anonymous
April 11, 2006
see
static private void MethodX(float x)
...
is not a generic method, if you are using MyClass.Method<float>(x), the system cannot possibly bind the call to the non-generic method - Anonymous
July 17, 2006
You can do this with C++ and templates evaluated at compile time (and cool things such as specialization) but because all this happens during runtime, there's no way to bind. Also, there's not much you can do with the type variable as long as you don't restrict it to T : class, where you can use the 'is' operator if I remember well.
I hope there will be some added stuff for generics, but because dotnetfx3 has no CLR changes (will run on 2.0 CLR), I don't expect improvement to generics until 3.5/4.0
Gabor