27

I have three class as following:

public class TestEntity { }

public class BaseClass<TEntity> { }

public class DerivedClass : BaseClass<TestEntity> { }

I already get the System.Type object of DerivedClass using reflection in runtime. How can I get the System.Type object of TestEntity using reflection?

Thanks.

gabe
  • 1,873
  • 2
  • 20
  • 36
lucn
  • 368
  • 1
  • 4
  • 10

4 Answers4

41

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

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

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

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

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

Rafal
  • 12,391
  • 32
  • 54
6

You can use the BaseType property. The following code would be resilient for changes in the inheritance (e.g. if you add another class 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:
GetBaseType(typeof(DerivedClass))
Eli Arbel
  • 22,391
  • 3
  • 45
  • 71
0
var derivedType = typeof(DerivedClass);
var baseClass = derivedType.BaseType;
var genericType = baseClass.GetGenericArguments()[0];
ken2k
  • 48,145
  • 10
  • 116
  • 176
0

It think this should work:

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

Or

var someObject = new DerivedClass();
var firstGenericArgumentType = someObject.GetType().BaseType.GetGenericArguments().FirstOrDefault();
Maarten
  • 22,527
  • 3
  • 47
  • 68