Why GetType returns System.Int32 instead of Nullable? [duplicate]

GetType() is a method of object. To call it, the Nullable<T> struct must be boxed. You can see this in the IL code: //int? x = 5; IL_0000: ldloca.s 00 IL_0002: ldc.i4.5 IL_0003: call System.Nullable<System.Int32>..ctor //Console.WriteLine(x.GetType()); IL_0008: ldloc.0 IL_0009: box System.Nullable<System.Int32> IL_000E: callvirt System.Object.GetType IL_0013: call System.Console.WriteLine Nullable types are treated specially by CLR; it … Read more

Nullable type is not a nullable type?

According to the MSDN : Calling GetType on a Nullable type causes a boxing operation to be performed when the type is implicitly converted to Object. Therefore GetType always returns a Type object that represents the underlying type, not the Nullable type. When you box a nullable object, only the underlying type is boxed. Again, … Read more

C# ‘is’ operator performance

Using is can hurt performance if, once you check the type, you cast to that type. is actually casts the object to the type you are checking so any subsequent casting is redundant. If you are going to cast anyway, here is a better approach: ISpecialType t = obj as ISpecialType; if (t != null) … Read more

Type Checking: typeof, GetType, or is?

All are different. typeof takes a type name (which you specify at compile time). GetType gets the runtime type of an instance. is returns true if an instance is in the inheritance tree. Example class Animal { } class Dog : Animal { } void PrintTypes(Animal a) { Console.WriteLine(a.GetType() == typeof(Animal)); // false Console.WriteLine(a is … Read more