Identification of the generic class type using reflection

Is there a way to detect the type specified in the general parameter in the class?

For example, I have three classes below:

public class Customer { } public class Repository<T> { } public class CustomerRepository : Repository<Customer> { } public class Program { public void Example() { var types = Assembly.GetAssembly(typeof(Repository<>)).GetTypes(); //types contains Repository, and CustomerRepository //for CustomerRepository, I want to extract the generic (in this case, Customer) } } 

For each repository object returned, I would like to indicate what type is specified.
Is it possible?

EDIT

Thanks to @CuongLe, I got this that works, but it looks dirty .... (also help from resharper;))

 var types = Assembly.GetAssembly(typeof(Repository<>)) .GetTypes() .Where(x => x.BaseType != null && x.BaseType.GetGenericArguments().FirstOrDefault() != null) .Select(x => x.BaseType != null ? x.BaseType.GetGenericArguments().FirstOrDefault() : null) .ToList(); 
0
source share
2 answers

Suppose you now hold the type CustomerRepository , choosing from the list of types:

 var customerType = typeof(CustomerRepository).BaseType .GetGenericArguments().First(); 

Edit: You do not need to trust Re-Sharper 100%. Since you are doing Where to select the entire type whose BaseType not null , check once again in Select . For more FirstOrDefault actually return null , this code is optimized:

  Assembly.GetAssembly(typeof(Repository<>)) .GetTypes() .Where(x => x.BaseType != null) .Select(x => x.BaseType.GetGenericArguments().FirstOrDefault()) .ToList(); 
+2
source
+1
source

All Articles