John Farrell
John Farrell

Reputation: 24754

Can Object.GetType() ever return null?

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();
}

Upvotes: 8

Views: 2857

Answers (5)

jason
jason

Reputation: 241641

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

Upvotes: 5

Wim
Wim

Reputation: 12082

Basically, no, it can't (ever return null) and won't.

Upvotes: 0

AdaTheDev
AdaTheDev

Reputation: 147224

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

Upvotes: 14

Neil N
Neil N

Reputation: 25258

http://msdn.microsoft.com/en-us/library/system.object.gettype(VS.85).aspx

MSDN only lists a type object as the return value.

I'd imagine other than that all you can get is a "not set to an instance of an object" exception (or maybe its null reference) Because MSDN does say INSTANCE.

Upvotes: 0

Jake Pearson
Jake Pearson

Reputation: 27717

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.

Upvotes: 2

Related Questions