tags:

views:

123

answers:

6

Can anyone help me? I can't figure out what I am doing wrong but it seems like there will be a simple solution:

Normally you can use is like this:

if (theObject is MyClass) ...

but if you want to specify the type it checks for at runtime this doesnt compile

Type theType = ...
if (theObject is theType) ...

I tried doing this:

if (theObject.GetType() == theType) ...

But that only works if theType is that exact type and doesnt take into account inheritance like the is statement does

I'm sure a solution exists (probably using generics) but I can't think of one right now (its the kind of thing you suddenly remember how to do the moment you click 'Post')

+13  A: 

It sounds like you want IsAssignableFrom(), as in

if (theType.IsAssignableFrom(theObject.GetType())) ...
ladenedge
You got it backwards. The correct form is "theType.IsAssignableFrom(theObject.GetType())"
Kennet Belenky
You're right, I neglected the OP's context. I'll reverse it - thank you!
ladenedge
+5  A: 

Use Type.IsAssignableFrom()

Kennet Belenky
+2  A: 

You are looking for the Type.IsSubclassOf or Type.IsAssignableFrom method, depending on the situation (usually the latter rather than the former). The latter is slightly more useful as it will return true if the type is the same as the one you want to check for whereas, clearly, a type is not a sub-class of itself. Also, IsSubclassOf doesn't take into account generics constraints whereas IsAssignableFrom will.

Jeff Yates
A: 

Have you tried using IsAssignableFrom()?

if( typeof(MyBaseClass).IsAssignableFrom(theType.GetType()) );
JeremySpouken
A: 

You can use Type.IsSubclassOf to do this, in addition to the equals comparison.

Matias Valdenegro
you are wrong, it is opposite method, from msdn: "If the IsSubclassOf is the converse of IsAssignableFrom. That is, if t1.IsSubclassOf(t2) is true, then t2.IsAssignableFrom(t1) is also true."
Andrey
+1  A: 

The Type.IsAssignableFrom answers are correct. The reason the way you tried doesn't work is because there are 2 kinds of "type". The first one is the compile time type which is what if (theObject is MyClass) uses. It is also the kind used in Generics.

The other kind is of type System.Type which is what your 2nd one is. You can convert from a compile-time to a System.Type by using the typeof keyword. The equivilent of your 2nd example would be if (theObject is typeof(MyClass)) which won't compile.

There might be a more official or correct name for compile-time types, so if anyone knows it feel free to edit or comment it in.

Davy8