How to check if a type implements a specific interface using C# reflection

Hackered
Friday, July 31, 2015
by Sean McAlinden

I recently built an extension to create a complex and deep object graphs from SpecFlow tables (table.CreateDeepInstance<>), as you can imagine I had to dust off my reflection hat.

As I needed to handle simple type, array, list and dictionary properties, it was imperative I could ascertain the correct property type.

In reflection there is a really useful method called FindInterfaces which finds all the implemented or inherited interfaces for a given type.

Type[] Type.FindInterfaces(TypeFilter filter, object filterCriteria)

The TypeFilter parameter requires a delegate method which accepts a type and the filterCriteria you pass into the second filterCriteria parameter for example:

private static bool MyTypeFilter(Type type, object filterCriteria)
{
    // implementation ommited
}

The type filter in my case can be fairly simple and generic as I just need to know whether a type implements or inherits a list or dictionary interface.

private static bool MyInterfaceFilter(Type type, Object filterCriteria)
{
    return type.ToString().Contains(filterCriteria.ToString());
}

As you can see, I'm simply checking whether a type name contains my filterCriteria.

Now I am ready to call Type.FindInterfaces to perform my check.

As FindInterfaces returns an array of types (Type[]), if the length of the returned array is greater than zero we know the passed in interface has been implemented or inherited.

Check if a type inherits from IList<>

This method verifies whether a given type inherits or implements the generic IList<> interface.

private static bool IsGenericListProperty(PropertyInfo propertyInfo)
{
    return propertyInfo
      .PropertyType
      .FindInterfaces(MyInterfaceFilter, typeof(IList<>).FullName).Length > 0;
}

Check if a type inherits from IDictionary<,>

This method verifies whether a given type inherits or implements the generic IDictionary<> interface.

private static bool IsGenericDictionaryProperty(PropertyInfo propertyInfo)
{
    return propertyInfo
      .PropertyType
      .FindInterfaces(MyInterfaceFilter, typeof(IDictionary<,>).FullName).Length > 0;
}

That's all folks, hope this has been useful.