none
What interface implemented by a type ? RRS feed

  • Question

  • I need information about what interface implemented by current type, but I just found GetInterfaces that return all interfaces implemented including from base-class or interface implemented by current interface.

    public class A: IList<int>
    {
    }
    
    public class B: A, ICloneable 
    {
    }

    Now suppose I want to know what interface implemented by class B, it should return only ICloneable, but GetInterfaces method will return all interfaces inlcuding IList`1 and its base interface.

    My question is possible to do that ?

    So if class A, it should only return IList`1 interface and class B only return ICloneable ?


    It's hard to be advanced programmer

    Wednesday, July 25, 2012 7:14 AM

Answers

  • It's possible, but expensive.

    A first approximation is the following:

    var uniqueInterfaces = typeof (B).GetInterfaces ().Except (typeof (B).BaseType.GetInterfaces ()).ToList ();

    This essentially gets all the interfaces from some type B, and removes all the interfaces implemented by the base type. Since the list of interfaces implemented by the base type includes all the interfaces implemented by its ancestors, this will only leave the interfaces implemented by B.

    This works to a point: for the class A of your example it correctly returns IList<>, but it obviously also returns ICollection<>, IEnumerable<> and IEnumerable. If you want to remove those as well, you need to do a little more work. One way to do this would be:

    var interfaces = typeof (A).GetInterfaces ().Except (typeof (A).BaseType.GetInterfaces ());
    var derivedInterfaces = interfaces.SelectMany (x => x.GetInterfaces ()).Distinct ();
    var uniqueInterfaces = interfaces.Except (derivedInterfaces).ToList ();
    

    Not extremely efficient, maybe, but reasonably readable.

    HTH
    --mc

    • Proposed as answer by Tim Copenhaver Wednesday, July 25, 2012 8:20 PM
    • Marked as answer by IRW7 Monday, July 30, 2012 1:36 PM
    Wednesday, July 25, 2012 4:41 PM