Skip to content

Getting declared type of a NulllableType variable

If the GetType method is called on a variable of NullableType then you will get the underlying type instead of the NullableType. This is because of boxing that occurs when the type object is converted to Object as documented at MSDN. So how do you get the declared type if you have a variable of NullableType? Here is the code that will return the Type object of the declared type of the NullableType variable.

        private static Type GetUnderlyingType(T t)
            return typeof(T);

The code above uses Generics and typeof operator to obtain the underlying NullableType. The trick here is to call typeof on the type itself and not the variable. This is not usually possible when you just have a variable but the power of Generics allows you to do so. So, say if you have declared a variable of NullableType int

int? i;

the code in GetUnderlyingType method above does the equivalent of


to return the underlying NullableType. To further understand the difference between calling GetType on a variable and using typeof operator on the Type itself, look at the following code.

	private static void PrintType(T t)
            Console.WriteLine("{0}, {1}", t.GetType().FullName, typeof(T).FullName);

Calling GetType on variable t returns the underlying type where as using typeof operator on Generic type parameter T returns the declared type of variable t.
Given a variable we can further test if the variable holds a NullableType by using the following code.

        private static bool IsNullable(T t)
            Type tx = GetUnderlyingType(t);
            return tx.IsGenericType && tx.GetGenericTypeDefinition() == typeof(Nullable<>);

The code above obtains the underlying type first and then tests if the type is Generic, and if it is Generic type then it tests for NullableType.