开发者

Can Object.GetType() ever return null?

开发者 https://www.devze.com 2022-12-19 08:51 出处:网络
Merely curious. Is there any time when calling .GetType() on an object will return null? Hypothe开发者_StackOverflow社区tical usage:

Merely curious.

Is there any time when calling .GetType() on an object will return null?

Hypothe开发者_StackOverflow社区tical 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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消