Identify Nullable Types
July 30, 2012
Posted by on
I had a need of using the reflection to go through different properties of a class and examine if it is a nullable type.
I have learned an interesting thing that GetType() method upon the property would not let us know if it is a nullable type. Moreover, there is no direct method in reflection to check that up, (like IsVisible or IsValueType).
I found an interesting write up from MSDN that explained the issues I faced and posted a solution to it as well.
How to: Identify a Nullable Type (C# Programming Guide)
The following code lets us know if it is a Nullable type. But before that we need to get the type from non-GetType() way.
foreach (var property in typeof(Request).GetProperties())
Type type = property.PropertyType;
//Check the value of non nullable fields
if (type.Is.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))