Checking to see if a generic class is inherited from an interface
- by SnOrfus
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.