2

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?

Community
  • 1
  • 1
Kevin Cruijssen
  • 9,153
  • 9
  • 61
  • 135
  • Something like this http://stackoverflow.com/questions/31855832/how-to-determine-if-class-inherits-dictionary ? – Eser Aug 11 '15 at 10:12
  • Aside from the direct answer to your question (Chris already suggested use of the is operator), I would strongly suggest you to rethink the design. If base class is supposed to know about derived classes (but not all of them), then it could be possible that you need the second level of base class which implements the desired interface and is used to cover that subset of derived classes. If you think that way, you might also come to a better understanding of the problem you're modeling. – Zoran Horvat Aug 11 '15 at 10:24

1 Answers1

8

Simply us 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() )
    ....
Chris
  • 5,442
  • 17
  • 30
  • Perfect! The second one with the type argument at runtime was indeed what I was looking for. EDIT: Also, ReSharper said I should replace `t.IsAssignableFrom(this.GetType())` to `type.IsInstanceOfType(this)` – Kevin Cruijssen Aug 11 '15 at 10:47
  • @KevinCruijssen IIRC `IsInstanceOfType` just calls `IsAssignableFrom`, so either way will do! – Chris Aug 11 '15 at 10:52