Search code examples
c#genericstypesinterfaceimplementation

Check if object implements specific generic interface


I have multiple classes (simplified for explaining purposes):

public class A : BaseClass,
    IHandleEvent<Event1>,
    IHandleEvent<Event2>
{
}

public class B : BaseClass,
    IHandleEvent<Event3>,
    IHandleEvent<Event4>
{
}

public class C : BaseClass,
    IHandleEvent<Event2>,
    IHandleEvent<Event3>
{
}

In my "BaseClass" I have a method where I want to check whether or not the Child-class implements an IHandleEvent of a specific event.

public void MyMethod()
{
    ...
    var event = ...;
    ...
    // If this class doesn't implement an IHandleEvent of the given event, return
    ...
}

From this SO-answer I know how to check if an object implements a generic interface (implements IHandleEvent<>), like this:

if (this.GetType().GetInterfaces().Any(x =>
    x.IsGenericType && x.GenericTypeDefinition() == typeof(IHandleEvent<>)))
{
    ... // Some log-text
    return;
}

But, I don't know how to check if an object implements a SPECIFIC generic interface (implements IHandleEvent<Event1>). So, how can this be checked in the if?


Solution

  • Simply use the is or as operator:

    if( this is IHandleEvent<Event1> )
        ....
    

    Or, if the type argument isn't known at compile time:

    var t = typeof( IHandleEvent<> ).MakeGenericType( /* any type here */ )
    if( t.IsAssignableFrom( this.GetType() )
        ....