bashis
bashis

Reputation: 1243

C# - How to get the concrete type of base generic

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?

Upvotes: 1

Views: 2301

Answers (1)

Lucas Trzesniewski
Lucas Trzesniewski

Reputation: 51430

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;
}

Upvotes: 6

Related Questions