Confusing question, I know. Given the following:
class Test
{
public static void GenericFunc<T>(T SomeType)
{
System.Console.WriteLine("typeof(T): " + typeof(T).Name);
System.Console.WriteLine("SomeType.GetType(): " + SomeType.GetType().Name);
}
}
public class BaseType
{
public void RunTest() { Test.GenericFunc(this); }
}
public class DerivedType : BaseType { }
The following code produces interesting output:
DerivedType Derived = new DerivedType();
Derived.RunTest();
// output:
// typeof(T): BaseType
// SomeType.GetType(): DerivedType
However, this behaves as I would expect:
Test.GenericFunc(new Derived());
// output:
// typeof(T): DerivedType
// SomeType.GetType(): DerivedType
Can anyone help me understand the mechanism here that’s causing T to be evaluated as BaseType in the first case?
Thanks in advance!
Because this:
Is basically equivalent to:
Therefore the
GenericFuncgets instatiated at compile time withT = BaseType. However thethisobject you are passing in at runtime is the derived type which you get bySomeType.GetType().In the second case the compiler infers the type as
DerivedTypedirectly from the usage and thereforeGenericFuncgets instatiated withT = DerivedType.