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

  • Thread starter Thread starter Johndow
  • Start date Start date
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
 
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.
 
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
 
Back
Top