简体   繁体   中英

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

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.

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.

基本上,不,它不能(永远不会返回null),也不会。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM