Home All Groups Group Topic Archive Search About

[Reflection] best way to know if a Type implements an interface

Author
12 May 2007 1:07 PM
Voivod
Suppose I have an interface IPlugin, and a Type myType.

What's the best way to ask myType if it implements the IPlugin
interface?

I came out with this, but I don't know if there are better
alternatives:
bool implementsIPlugin = typeof(IPlugin).IsAssignableFrom(myType);

Author
12 May 2007 2:52 PM
Jon Skeet [C# MVP]
Voivod <francesco.pi***@gmail.com> wrote:
> Suppose I have an interface IPlugin, and a Type myType.
>
> What's the best way to ask myType if it implements the IPlugin
> interface?
>
> I came out with this, but I don't know if there are better
> alternatives:
> bool implementsIPlugin = typeof(IPlugin).IsAssignableFrom(myType);

Seems like a very good way to me. I can't remember off-hand whether it
will return true if myType is an interface deriving from IPlugin though
- one to check.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet   Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Author
13 May 2007 11:38 PM
Tigger
On May 12, 11:52 pm, Jon Skeet [C# MVP] <s***@pobox.com> wrote:
Show quote
> Voivod <francesco.pi***@gmail.com> wrote:
> > Suppose I have an interface IPlugin, and a Type myType.
>
> > What's the best way to ask myType if it implements the IPlugin
> > interface?
>
> > I came out with this, but I don't know if there are better
> > alternatives:
> > bool implementsIPlugin = typeof(IPlugin).IsAssignableFrom(myType);
>
> Seems like a very good way to me. I can't remember off-hand whether it
> will return true if myType is an interface deriving from IPlugin though
> - one to check.
>
> --
> Jon Skeet - <s***@pobox.comhttp://www.pobox.com/~skeet  Blog:http://www.msmvps.com/jon.skeet
> If replying to the group, please do not mail me too


if (myType is IPlugin)
{
  IPlugin myPlugin = (IPlugin)myType;
  // do stuff
}

// or

IPlugin myPlugin = myType as IPlugin;

if (myPlugin!=null)
{
  // do stuff
}

AddThis Social Bookmark Button