[ACCEPTED]-How to get base class's generic type parameter?-reflection

Accepted answer
Score: 40

I assume that your code is just a sample 6 and you don't explicitly know DerivedClass.

var type = GetSomeType();
var innerType = type.BaseType.GetGenericArguments()[0];

Note that 5 this code can fail very easily at run time 4 you should verify if type you handle is 3 what you expect it to be:

     && type.BaseType.GetGenericTypeDefinition() == typeof(BaseClass<>))

Also there can 2 be deeper inheritance tree so some loop 1 with above condition would be required.

Score: 6

You can use the BaseType property. The following 3 code would be resilient for changes in the 2 inheritance (e.g. if you add another class 1 in the middle):

Type GetBaseType(Type type)
   while (type.BaseType != null)
      type = type.BaseType;
      if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(BaseClass<>))
          return type.GetGenericArguments()[0];
   throw new InvalidOperationException("Base type was not found");

// to use:
Score: 0
var derivedType = typeof(DerivedClass);
var baseClass = derivedType.BaseType;
var genericType = baseClass.GetGenericArguments()[0];


Score: 0

It think this should work:

var firstGenericArgumentType = typeof(DerivedClass).BaseType.GetGenericArguments().FirstOrDefault();


var someObject = new DerivedClass();
var firstGenericArgumentType = someObject.GetType().BaseType.GetGenericArguments().FirstOrDefault();


More Related questions