Determine if a class implements a very specific interface

c#, inheritance, interface, reflection

Solution

I had a try because it sounded like fun, and this works for your example:

bool ImplementsIFooDirectly(Type t) {
    if (t.BaseType != null && ImplementsIFooDirectly(t.BaseType)) { 
        return false; 
    }
    foreach (var intf in t.GetInterfaces()) {
        if (ImplementsIFooDirectly(intf)) { 
            return false;
        }
    }
    return t.GetInterfaces().Any(i => i == typeof(IFoo));
}

results:

ImplementsIFooDirectly(typeof(IFoo)); // false
ImplementsIFooDirectly(typeof(Bar)); // false
ImplementsIFooDirectly(typeof(Foo)); // true
ImplementsIFooDirectly(typeof(IBar)); // true

It doesn't look for all interfaces derived from `IFoo`, it just travels up the inheritance / interface implementation chain and see if `IFoo` is present at any level other than the exact level of the type.

It also detects if the interface is inherited via base type. Not sure if that is what you want.

Still, as others have said already, if this is really a requirement for you, then you might have a problem with your design. (EDIT: Just noticed your question is purely hypothetical. Then it's fine of course :))

Problem

There are tons of questions about this topic, but I have a slightly altered version of it. We have the following code: ``` interface IFoo { } interface IBar : IFoo { } class Foo : IFoo { } class Bar : IBar { } bool Implements_IFoo(Type type) { /* ??? */ } ``` Now, the twist of the story: the method `Implements_IFoo` should only return true when the Type implements IFoo only and not any of the interfaces derived from IFoo. To illustrate here are some examples of this method: ``` Implements_IFoo(typeof(Foo)); // Should return true Implements_IFoo(typeof(Bar)); // Should return false as Bar type // implements an interface derived from IFoo ``` Note that there can be numerous interfaces derived from IFoo and you do not necessarily know about their existence. The obvious method is to find all interfaces derived from IFoo through reflection and then just check the typeof(Bar).GetInterfaces() is any of those are present in there. But I was wondering if someone can come up with a more elegant solution. PS The question originates from some code I found that uses this check on classes (`if(obj.GetType() == typeof(BaseClass)) { ... }`). We are replacing classes with interfaces now that particular code. Also, just in case - I am implementing this check as a boolean flag, so this question is purely hypothetical.

Original source