Matheus Simon
Matheus Simon

Reputation: 696

C# Reflection - Get Generic Argument type of Super class from within the Base class

Consider the classes:

public class Super : Base<Test, Super>
{
    public Super Next { get; set; }
}

public class Base<TArg, TSuper>
{
    public Type GetTestArgument()
    {
        Type[] arguments = typeof(TSuper).GetProperty("Next").PropertyType.BaseType.GetGenericTypeDefinition().GetGenericArguments();
        // arguments is set to [ TArg, TSuper ] instead of [ Test, Super ]
        return arguments[0]; // should be Test
    }
}

Does anyone know how to get the generic type from within the base class without calling typeof(TArg) because I'll be iterating through other super classes properties and it must be via deeper reflection.

Thanks.

Upvotes: 1

Views: 317

Answers (1)

canton7
canton7

Reputation: 42245

You've got a call to GetGenericTypeDefinition(), which you probably don't want. I.e.:

typeof(TSuper).GetProperty("Next").PropertyType.BaseType.GetGenericArguments()

typeof(TSuper).GetProperty("Next").PropertyType.BaseType returns the type Base<Test, Super>. So calling GetGenericArguments() on it returns [Test, Super].

Calling GetGenericTypeDefinition() on that gives you Base<TArg, TSuper>, and calling GetGenericArguments() on it returns [TArg, TSuper].

Upvotes: 2

Related Questions