Which one is the preferred way to get the type?
You can only use typeof()
when you know that type at compile time, and you're trying to obtain the corresponding Type
object. (Although the type could be a generic type parameter, e.g. typeof(T)
within a class with a type parameter T
.) There don't need to be any instances of that type available to use typeof
. The operand for typeof
is always the name of a type or type parameter. It can't be a variable or anything like that.
Now compare that with object.GetType()
. That will get the actual type of the object it's called on. This means:
GetType
on)One odd point: GetType
will give unexpected answers on nullable value types due to the way that boxing works. A call to GetType
will always involve boxing any value type, including a nullable value type, and the boxed value of a nullable value type is either a null reference or a reference to an instance of a non-nullable value type.