Dov
Dov

Reputation: 16156

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.

Upvotes: 2

Views: 250

Answers (3)

Timothy Carter
Timothy Carter

Reputation: 15785

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.

Upvotes: 1

Reed Copsey
Reed Copsey

Reputation: 564363

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.

Upvotes: 8

Alistair Evans
Alistair Evans

Reputation: 36473

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

I think that should do it.

Upvotes: 1

Related Questions