Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Object.GetType() ever return null?

Tags:

c#

types

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();
}
like image 232
John Farrell Avatar asked Feb 04 '10 15:02

John Farrell


People also ask

Can Typeof return null?

The typeof operator returns "object" for objects, arrays, and null.

Is GetType slow?

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.


3 Answers

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

like image 151
AdaTheDev Avatar answered Oct 21 '22 12:10

AdaTheDev


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.)

like image 25
jason Avatar answered Oct 21 '22 12:10

jason


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.

like image 2
Jake Pearson Avatar answered Oct 21 '22 11:10

Jake Pearson