ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

ImplementsInterfaces(List<Type> types)

Determines if a class object implements an interface type and returns a list of types it actually implements. If no matching type is found an empty list will be returned.

Source

public static List<Type> ImplementsInterfaces(this object obj, List<Type> interfaces)
{
    if (obj == null || interfaces == null)
        return new List<Type>();

    var filter = new System.Reflection.TypeFilter(
        (Type typeObj, object criteriaObj) => { return typeObj.ToString() == criteriaObj.ToString() ? true : false; }
        );

    Func<Type, Type> func = (Type t) => { return obj.GetType().FindInterfaces(filter, t.FullName).Length > 0 ? t : null; };

    return (from i in interfaces select func(i)).Where(t => t == null ? false : true).ToList();
}

Example

var t = new Test();
if (t.ImplementsInterface(new List<Type> { typeof(ITest) }).Count > 0)
 { 
                //Do Something
 }

Author: James Levingston

Submitted on: 19 okt. 2010

Language: C#

Type: System.Object

Views: 4609