Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you use the IS operator with a Type on the left side?

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.

like image 963
Dov Avatar asked Nov 23 '25 21:11

Dov


2 Answers

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.

like image 145
Reed Copsey Avatar answered Nov 25 '25 09:11

Reed Copsey


if( !( propertyInfo.PropertyType.isSubClassOf( typeof(DataTable) ) )
 continue;

I think that should do it.

like image 28
Alistair Evans Avatar answered Nov 25 '25 11:11

Alistair Evans



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!