typeof generic and casted type

  • A+
Category:Languages

Let's say we have generic method:

public void GenericMethod<T>(T item) {     var typeOf = typeof(T);     var getType = item.GetType(); } 

And we are invoking it with the following parameters:

GenericMethod(1) GenericMethod((object) 1) 

The results are:

typeOf = System.Int32 getType = System.Int32 

and

typeOf = System.Object getType = System.Int32 

Can someone explain me why typeof integer casted to object returns System.Object, but .GetType() returns System.Int32?

 


typeof returns the static (compile-time) type of the generic parameter T.

GetType returns the dynamic (run-time) type of the value contained in variable item.


The difference is easier to see if you make your method non-generic. Let's assume that B is a subtype of A:

public void NonGenericMethod(A item) {     var typeOf = typeof(A);     var getType = item.GetType(); } 

In that case, calling NonGenericMethod(new B()) would yield

A B 

Recommended further reading:


Now, you might ask: Why did you use NonGenericMethod(A item) in your example instead of NonGenericMethod(B item)? That's a very good question! Consider the following (non-generic) example code:

public static void NonGenericMethod(A item) {     Console.WriteLine("Method A");     var typeOf = typeof(A);     var getType = item.GetType(); } public static void NonGenericMethod(B item) {     Console.WriteLine("Method B");     var typeOf = typeof(B);     var getType = item.GetType(); } 

What do you get when you call NonGenericMethod((A) new B()) (which is analogous to the argument (object) 1 in your example)?

Method A A B 

Why? Because overload resolution is done at compile-time, not at run-time. At compile-time, the type of the expression (A) new B() is A, just like the compile-time type of (object) 1 is object.

Recommended further reading:

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: