Check if a certain interface is implemented


Today a coworker of mine needed to know how he could check a property of a certain class implemented a certain interface. In this case it was the System.Collections.IEnumerable interface. The following code is a custom class to demonstrate that it’s property implements the interface System.Collections.IEnumerable.

using System; using System.Collections.Generic; using System.Text; namespace InterfaceCheck { public class ClassToCheck { private List stringsProperty; public List StringsProperty { get { return stringsProperty; } set { stringsProperty = value; } } }

The property is of type System.Collections.Generics.List<String>. If everything is correct this property will return that it implements the IEnumerable interface because the List<T> implements it. The following code is checking it:

ClassToCheck ctc = new ClassToCheck(); foreach (PropertyInfo propertyInfo in ctc.GetType().GetProperties()) { if (propertyInfo.PropertyType.GetInterface("System.Collections.IEnumerable")
!= null) Console.WriteLine("Interface is implemented"); else
Console.WriteLine("Interface not implemented"); }

It's following piece of code that does the checking: if (propertyInfo.PropertyType.GetInterface( "System.Collections.IEnumerable") != null) If the property implements the IEnumerable interface it will return it, if not it will return null.