Click to Rate and Give Feedback
MSDN
MSDN Library
Visual Studio 2005
Visual Studio
Visual C#
Nullable Types
 How to: Identify a Nullable Type
This page is specific to
Microsoft Visual Studio 2005/.NET Framework 2.0

Other versions are also available for the following:
C# Programming Guide
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 attempt to obtain type information from Nullable variables at runtime 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 above.

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

See Also

Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
Could you elaborate on getting an object's type at run-time without using GetType()?      darren.wright71   |   Edit   |   Show History
This is the fifth time I've been directed to this article; I'm going round in circles.
Tags What's this?: Add a tag
Flag as ContentBug
What examples are this ?      Identify a Nullable Type   |   Edit   |   Show History

With these examples i better like this:

if (typeof(T).GUID.ToString() == "9a9177c7-cf5f-31ab-8495-96f58ac5df3a")

{

}

Tags What's this?: Add a tag
Flag as ContentBug
Processing
© 2009 Microsoft Corporation. All rights reserved. Terms of Use | Trademarks | Privacy Statement | Site Feedback
Page view tracker