views:

125

answers:

3

I have a method I'm writing that uses reflection to list a class's static properties, but I'm only interested in those that are of a particular type (in my case, the property must be of a type derived from DataTable). What I would like is something like the if() statement in the following (which presently always returns true):

PropertyInfo[] properties = ( typeof(MyType) ).GetProperties( BindingFlags.Public
    | BindingFlags.Static );

foreach( PropertyInfo propertyInfo in properties ) {
    if( !( propertyInfo.PropertyType is DataTable ) )
        continue;

    //business code here
}

Thanks, I'm stumped.

+1  A: 
if( !( propertyInfo.PropertyType.isSubClassOf( typeof(DataTable) ) )
 continue;

I think that should do it.

Kazar
That will fail if PropertyType is a DataTable, though.
Reed Copsey
I didn't know that, makes sense though.
Kazar
+8  A: 

You need to use Type.IsAssignableFrom instead of the "is" operator.

This would be:

if( !( DataTable.IsAssignableFrom(propertyInfo.PropertyType) )

DataTable.IsAssignableFrom(propertyInfo.PropertyType) will be true if PropertyType is a DataTable or a subclass of DataTable.

Reed Copsey
+1  A: 
if (!(typeof(DataTable).IsAssignableFrom(propertyInfo.PropertyType)))

The ordering here perhaps seems a little backwards, but for Type.IsAssignableFrom, you want the type you need to work with to come first, and then the type you're checking.

Timothy Carter