The typeof operator takes a type as a parameter. It is resolved at compile time. The GetType method is invoked on an object and is resolved at run time. The first is used when you need to use a known Type, the second is to get the type of an object when you don't know what it is.
1500 milliseconds for the first approach and approx. 2200 milliseconds for the second. (code and timings corrected - doh!)
The typeof is an operator keyword which is used to get a type at the compile-time. Or in other words, this operator is used to get the System.
GetType Method is used to find the type of the current instance. This method returns the instances of the Type class that are used for consideration. Syntax: public Type GetType (); Return Value: This method return the exact runtime type of the current instance.
Is anyone aware of any differences between typeof(T) where T : struct
, for example, vs. t.GetType() where t is a System.Object
?
ILdasm shows that typeof(T) uses System.Type::GetTypeFromHandle(RuntimeTypeHandle handle)
, and the other is just plain System.Object::GetType()
. The implementations are [MethodImpl(MethodImplOptions.InternalCall)]
, so the methods are defined in native code in the CLR. So, I'm just wondering if anyone is aware of any reason to prefer one over the other?
EDIT: Let me clarify, I'm mostly interested in the cases where it doesn't seem to matter which you choose - that is, is there a performance difference, or any other reason? Thanks!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With