Hi here is my example let's say
class A { }
class B : A { }
void test<T>(T clazz)
{
Console.WriteLine("clazz type = {0} T type = {1}",
clazz.GetType().Name,
typeof(T).Name);
}
static void Main(string[] args)
{
A b = new B();
test(b);
Console.ReadLine();
}
The result is clazz= B T= A ????? why inference generic type doesn't take into account polymorphism ?
The result is clazz= B T= A ????? why inference generic type doesn't take into account polymorphism ?
Type inference is performed at compile time. The compile time type of the variable b
is A
, so the compiler infers that you meant:
test<A>(b);
The fact that the value of b
at execution time is B
is irrelevant, because that's too late for type inference.
As of C# 4 you can defer the type inference until execution time using dynamic
though:
dynamic b = new B();
test(b);
See more on this question at Stackoverflow