Can Object.GetType () return null?

Just curious.

Is there a time when calling .GetType() on an object returns null?

Hypothetical use:

 public Type MyMethod( object myObject ) { return myObject.GetType(); } 
+7
c # types
source share
5 answers

GetType on an object can never return null - at least it will have an object of type. if myObject is NULL then you will get an exception when trying to call GetType () anyway

+14
source share

No, it will not return null . But here's what you need to know!

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

(Original credit concept for Mark Gravell.)

+5
source share

If the myObject parameter is null, you cannot call GetType () on it. Thrown NullReferenceException. Otherwise, I think you will be fine.

+2
source share

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

MSDN only lists the type object as the return value.

I would suggest that all you can get is an exception "not configured on an instance of an object" (or maybe its null reference). Because MSDN says "INSTANCE".

0
source share

Basically, no, it cannot (ever return null) and will not.

0
source share

All Articles