471,122 Members | 1,237 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,122 software developers and data experts.

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

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
Mar 24 '06 #1
4 1554
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.

Mar 24 '06 #2
>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

--
Mattias Sjögren [C# MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Mar 24 '06 #3
Yes, that is exactly I am looking for. Thanks mattias!

"Mattias Sjögren" <ma********************@mvps.org> wrote in message
news:uz**************@TK2MSFTNGP11.phx.gbl...
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

--
Mattias Sjögren [C# MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.

Mar 24 '06 #4
You may want to read Jon Skeet's article on plug-ins and cast
exceptions.

http://www.yoda.arachsys.com/csharp/plugin.html

Mar 24 '06 #5

This discussion thread is closed

Replies have been disabled for this discussion.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.