System.Reflection.RuntimePropertyInfo - accessing actual datatype of property

  • Thread starter Thread starter Jay
  • Start date Start date
J

Jay

Is there a way to access the actual datatype of a property when
looking at the PropertyInfo?

For example:

Property defined:

public Nullable<DateTime> EndDate
{
get { return endDate; }
set { endDate = value; }
}

What we would like to do is while accessing the properties contained
in this class to find out the actual data type of each property. This
is because we are going to automatically assign values (using
reflection) to enforce validation rules.

Processing all properties:

foreach (PropertyInfo myPropertyInfo in myType.GetProperties())
{

}

Within this loop we'd like to know what the datatype the current
myPropertyInfo relates to.

The debugger shows the System.Reflection.RuntimePropertyInfo as:
{System.Nullable`1[System.DateTime] EndDate}. The problem is I cannot
figure a way to extract the "System.DateTime" portion from the
PropertyInfo object.

Anyone else know how this can be done?

TIA
 
First off, I tend to advise looking at PropertyDescriptors (via
TypeDescriptor.GetProperties) over PropertyInfo, as it will respect
virtual properties - but that is OT.

The problem here is that your property *isn't* a DateTime; it is
Nullable<DateTime>; to get the DateTime (when Nullable<T>) you could
probably do something like:

Type type = myPropertyInfo.PropertyType;
if (type.IsGenericType && type.GetGenericTypeDefinition() ==
typeof(Nullable<>)) {
type = type.GetGenericArguments()[0];
}

Marc
 
Back
Top