System.Reflection.RuntimePropertyInfo - accessing actual datatype of property

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
 
M

Marc Gravell

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top