0

If i have some class like this

interface IDeclaration<T> {...}

how should i implement check if instance of my particular class derived from IDeclaration<T> and if so - what is the type T in our particular case.

Thank you in advance

TakinosaJi
  • 400
  • 5
  • 13
  • Possible duplicate of [Reflection - Getting the generic parameters from a System.Type instance](http://stackoverflow.com/questions/293905/reflection-getting-the-generic-parameters-from-a-system-type-instance) – thehennyy Jun 10 '16 at 15:40

1 Answers1

1

IDeclaration is an interface, not a class. Classes can implement this interface, not derive from it.

To check whether a particular object implements the IDeclaration<T> interface, you could call the GetInterfaces method on that instance type and search for that particular interface like this:

var instance = ...

var @interface =
    instance.GetType()
        .GetInterfaces()
        .FirstOrDefault(i =>
            i.IsGenericType &&
            i.GetGenericTypeDefinition() == typeof (IDeclaration<>));

bool is_IDeclaration = @interface != null;

To get the generic type parameter (T), you can use the GetGenericArguments method like this:

if (is_IDeclaration)
{
    var typeof_T = @interface.GetGenericArguments()[0];
}
Yacoub Massad
  • 27,509
  • 2
  • 36
  • 62