Using Reflection to Determine if a Property Data Type is Nullable

You can easily determine if the data type of an object property is nullable using the following code:

Type t = objectReference.GetType();
Type pt;

// Test for Nullable
bool isNullable = pi.PropertyType.IsGenericType && pi.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>);
PropertyInfo pi = t.GetProperty(“MyPropertyName”);

if (isNullable)
{
   // Returns the basic data type without reference to Nullable (for example, System.Int32)
   pt = pi.PropertyType.GetGenericArguments()[0];
}

Best Regards,
Kevin McNeish
Chief Architect, MM .NET Application Framework
INETA Speaker
.NET MVP 2002-2009
www.oakleafsd.com 

Leave a Reply

Your email address will not be published. Required fields are marked *