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.

  1.  
  2. private static Type GetUnderlyingType<T>(T t)
  3. {
  4. return typeof(T);
  5. }
  6.  

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

  1. int? i;

the code in GetUnderlyingType method above does the equivalent of

  1. typeof(int?)

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.

  1.  
  2. private static void PrintType<T>(T t)
  3. {
  4. Console.WriteLine("{0}, {1}", t.GetType().FullName, typeof(T).FullName);
  5. }
  6.  

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.

  1.  
  2. private static bool IsNullable<T>(T t)
  3. {
  4. Type tx = GetUnderlyingType(t);
  5. return tx.IsGenericType && tx.GetGenericTypeDefinition() == typeof(Nullable<>);
  6. }
  7.  

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.