How to use "is" operator to a type from Reflection

J

Johndow

I have trouble to use "Is" operator to a type that is from reflection.
Basically, here is what I want to do, if Class1 type is not from reflection:
class Class1
{
}
public class Test
{
...
if (o is Class1) //to determine if object o is Class1, or is derivative
class of Class1
{
//object o can be cast to type
}
}

Now, Class1 is in different assembly, then I want to the samething, except
getting the Type from reflection

public class Test
{
...
Assembly objAssembly = Assembly.Load("MyDll");
Type t = objAssembly.GetType("MyDll.Class1");

//How to determine if object o is Class1, or is derivative class of Class1
????????
//if (o is Class1)
}


Thank a lot for your kind response
 
B

Bruce Wood

You should use the IsAssignableFrom() method of the Type class, like
this:

Assembly objAssembly = Assembly.Load("MyDll");
Type t = objAssembly.GetType("MyDll.Class1");
if (t.IsAssignableFrom(o))
{
... etc ...
}

I think that's the way it goes... I always get that IsAssignableFrom
thing backward. :) Anyway, I believe that's the method you want to
call. You can't use the "is" operator directly.
 
M

Mattias Sjögren

Now, Class1 is in different assembly, then I want to the samething, except
getting the Type from reflection

I think you're looking for typeof(Class1).IsAssignableFrom(t);


Mattias
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top