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…