Ahmed
Ahmed

Reputation: 371

Generic type inference doesnt take polymorphism into account

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 ?

Upvotes: 1

Views: 126

Answers (4)

evanmcdonnal
evanmcdonnal

Reputation: 48076

I don't think generics is the issue. It has to do with the the differences between typeof and GetType. GetType determines the type at run time, typeof determines the type of that instance at compile time. You declared the variable as type A, therefor that is the compile time type. Whether or not you assign an instance of an inherited class to that reference doesn't matter, you declared it as type A, that's what typeof returns. GetType is returning the type of the instance that reference currently points to, it doesn't care what you declared the variable as, but what the instance actually is.

Upvotes: 1

Maciej Stachowski
Maciej Stachowski

Reputation: 1728

typeof works at compile time, that is, it can't know about the polymorphism, because at that time it's not yet decided what type the actual object stored in the variable is. GetType(), however, works at runtime and can know the actual type.

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1500065

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);

Upvotes: 6

Ry-
Ry-

Reputation: 224877

When you pass an expression of type A to a parameter that determines a generic T, T is going to be A. The value of the object doesn’t come into play; it could be null and everything would still work.

(You can think of it as the type being determined at compile-time, but that’s not necessarily true, just necessarily possible.)

Upvotes: 0

Related Questions