Merely curious.
Is there any time when calling .GetType()
on an object will return null?
Hypothetical usage:
public Type MyMethod( object myObject )
{
return myObject.GetType();
}
The typeof operator returns "object" for objects, arrays, and null.
GetType() is 1.5-2 times as fast as typeof(class) . The buffered var seem to be 1.5-2 times as fast as Object.
GetType on an object can never return null - at the very least it will be of type object. if myObject is null, then you'll get an exception when you try to call GetType() anyway
No, it will not return null
. But here is a gotcha to be aware of!
static void WhatAmI<T>() where T : new() {
T t = new T();
Console.WriteLine("t.ToString(): {0}", t.ToString());
Console.WriteLine("t.GetHashCode(): {0}", t.GetHashCode());
Console.WriteLine("t.Equals(t): {0}", t.Equals(t));
Console.WriteLine("t.GetType(): {0}", t.GetType());
}
Here's the output for a certain T
:
t.ToString():
t.GetHashCode(): 0
t.Equals(t): True
Unhandled Exception: System.NullReferenceException: Object reference not set to
an instance of an object.
What is T
? Answer: any Nullable<U>
.
(Credit orginal concept to Marc Gravell.)
If the myObject parameter is null, then you won't be able to call GetType() on it. A NullReferenceException will be thrown. Otherwise, I think you will fine.
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