typeof generic and casted type
In GenericMethod((object) 1)
, T
will be object
. typeof reflects that.
But item.GetType();
is a virtual method and will execute at runtime on 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:
- Run-time type vs compile-time type in C#
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:
- When is the generic type resolved in c#?
The call to GetType gets resolved at runtime, while typeof is resolved at compile time. That is why it is giving different results. you can check here - When and where to use GetType() or typeof()?