C# test if object or type implements interface

If you have a type or an instance you can easily check if they support a specific interface.

To test if an object implements a certain interface:
if(myObject is IMyInterface) {
// object myObject implements IMyInterface
}

To test if a type implements a certain interface:
if(typeof(IMyInterface).IsAssignableFrom(typeof(MyType))) {
// type MyType implements IMyInterface
}

If you got a generic object and want to do a cast as well as a check if the interface you cast to is implemented the code is:

var myCastedObject = myObject as IMyInterface;

if(myCastedObject != null) {
// object myObject implements IMyInterface
}

Related posts:

Comments

comments powered by Disqus