Reputation: 1354
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')
Upvotes: 3
Views: 172
Reputation: 13439
It sounds like you want IsAssignableFrom(), as in
if (theType.IsAssignableFrom(theObject.GetType())) ...
Upvotes: 14
Reputation: 31606
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.
Upvotes: 1
Reputation: 62407
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.
Upvotes: 2
Reputation: 56417
You can use Type.IsSubclassOf to do this, in addition to the equals comparison.
Upvotes: 0
Reputation: 6302
Have you tried using IsAssignableFrom()?
if( typeof(MyBaseClass).IsAssignableFrom(theType.GetType()) );
Upvotes: 0