Share via


How to: Identify a Nullable Type (C# Programming Guide)

You can use the C# typeof operator to create a Type object that represents a Nullable type:

System.Type type = typeof(int?);

You can also use the classes and methods of the System.Reflection namespace to generate Type objects that represent Nullable types. However, if you try to obtain type information from Nullable variables at runtime by using the GetType method or the is operator, the result is a Type object that represents the underlying type, not the Nullable type itself.

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.

  int? i = 5;
  Type t = i.GetType();
  Console.WriteLine(t.FullName); //"System.Int32"

The C# is operator also operates on a Nullable's underlying type. Therefore you cannot use is to determine whether a variable is a Nullable type. The following example shows that the is operator treats a Nullable<int> variable as an int.

  static void Main(string[] args)
  {
    int? i = 5;
    if (i is int) // true
      //…
  }

Example

Use the following code to determine whether a Type object represents a Nullable type. Remember that this code always returns false if the Type object was returned from a call to GetType, as explained earlier in this topic.

if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) {…}

See Also

Reference

Nullable Types (C# Programming Guide)

Boxing Nullable Types (C# Programming Guide)