Checking to see if a generic class is inherited from an interface

Posted by SnOrfus on Stack Overflow See other posts from Stack Overflow or by SnOrfus
Published on 2010-03-30T22:45:25Z Indexed on 2010/03/30 22:53 UTC
Read the original article Hit count: 473

Filed under:
|
|

I've got a class that inherits from an interface. That interface defines an event that I'd like to subscribe to in the calling code. I've tried a couple of things, but they all resolve to false (where I know it's true). How can I check to see if a class implements a specific interface.

Here's what I've tried (note, the object in question is a usercontrol that implements MyInterface, stored in an array of controls, only some of which implement MyInterface - it is not null):

if (this.controls[index].GetType().IsSubclassOf(typeof(MyInterface)))
    ((MyInterface)this.controls[index]).Event += this.Handler;

if (this.controls[index].GetType().IsAssignableFrom(typeof(MyInterface)))
    ((MyInterface)this.controls[index]).Event += this.Handler;

if (this.controls[index].GetType() == typeof(MyInterface))
    ((MyInterface)this.controls[index]).Event += this.Handler;

All to no avail.

© Stack Overflow or respective owner

Related posts about c#

Related posts about inheritance