I’ve never liked having to pass a string to Type.GetInterface() to check if a type implements an interface.
This extension method to the Type class lets you check more neatly with a generic:
///<summary>
/// Extension methods for the <see cref=”Type”/> class.
///</summary>
public static class TypeExtensions
{
///<summary>
/// Returns whether the type implements the given interface
///</summary>
///<param name=”value”></param>
///<returns></returns>
public static bool ImplementsInterface<T>(this Type type)
{
var implements = false;
if (typeof(T).IsInterface)
{
var interfaceName = typeof(T).Name;
implements = (type.GetInterface(interfaceName) != null);
}
return implements;
}
}
Usage:
Assert.IsTrue(typeof(Stub).ImplementsInterface<IStub>());