views:

68

answers:

2

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.

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

You just have the IsAssignableFrom inverted.


For your case, however, the best way to do this test is the following for performance and clarity improvements:

if (this.controls[index] is MyInterface)
Dan Bryant
+2  A: 

I might be being dense but can't you just do:

MyInterface foo = this.controls[index] as MyInterface;
if (foo != null) { /* do stuff */ }

(and of course the real MyInterface should have a name starting with I)

AakashM