1

Assuming I have a class A:

class A : B<C>, IA
{

}

And I also have a method like this:

Type GetConcreteB<T>() where T : IA
{
//some code here...
}

In this method I would like to check if T inherits from any B (currently I wrap B into an interface IB which does the thing) and if it does, return the concrete type of C.

So, basically I want to return the concrete type of the base generic class only using the subclass type. Is there a way to achieve this?

bashis
  • 1,200
  • 1
  • 16
  • 35
  • possible duplicate of [Check if a class is derived from a generic class](http://stackoverflow.com/questions/457676/check-if-a-class-is-derived-from-a-generic-class) – Taher Rahgooy Aug 29 '15 at 17:40

1 Answers1

6

Using reflection, go through the class hierarchy until you find a B<T>, and then extract the T:

static Type GetConcreteB<T>()
    where T : IA
{
    var t = typeof(T);
    while (t != null) {
        if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(B<>))
            return t.GetGenericArguments()[0];

        t = t.BaseType;
    }

    return null;
}
Lucas Trzesniewski
  • 50,214
  • 11
  • 107
  • 158