Professional Documents
Culture Documents
http://msdn.microsoft.com/en-us/library/ms366789
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.
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.
See Also
Reference Nullable Types (C# Programming Guide) Boxing Nullable Types (C# Programming Guide)
1 of 4
5/25/2012 11:48 AM
http://msdn.microsoft.com/en-us/library/ms366789
Yes
No
Community Content
Simple trick to get Underlying nullable value if it exists
Given some type T, here's a simple way to always have the real (underlying type), regardless if it is nullable or not: var realType = Nullable.GetUnderlyingType(typeof(T)) ?? typeof(T);
3/30/2012 Wuzi
public static bool IsObjectNullable<T>(T? obj) where T : struct { // Always return true, since the object-type passed is guaranteed by the compiler to always be nullable return true; }
2 of 4
5/25/2012 11:48 AM
http://msdn.microsoft.com/en-us/library/ms366789
CAVEAT: This method works reliably only if called using the original object reference or an exact copy, as shown in the linked examples. However, if a nullable object is boxed to another Type (such as object, etc.) instead of remaining in its original Nullable<> form, this method will not work reliably. If the code calling this method is not using the original, unboxed object reference or an exact copy, it cannot reliably determine the object's nullability using this method. In most coding scenarios, to determine nullability one must instead rely on testing the original object's Type, not its reference (e.g., code must have access to the object's original Type to determine nullability). In these more common cases, IsTypeNullable is a reliable method of determining nullability (see link below). See the above link for further detail and examples. 10/14/2011 wmarkjones 10/14/2011 wmarkjones
3 of 4
5/25/2012 11:48 AM
http://msdn.microsoft.com/en-us/library/ms366789
4 of 4
5/25/2012 11:48 AM