Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get contained type in a List<T> through reflection?

Through reflection, is there some way for me to look at a generic List's contained type to see what type the collection is of? For example:

I have a simple set of business objects that derive from an interface, like this:

public interface IEntityBase{}  

public class BusinessEntity : IEntityBase   
{
    public IList<string> SomeStrings {get; set;}       
    public IList<ChildBusinessEntity> ChildEntities { get; set;}
} 

public class ChildBusinessEntity : IEntityBase{}

In the case where I am iterating through the properties of BusinessEntity through reflection, would there be a way for me to see if the objects nested inside those lists derived from IEntityBase?

Pseudocoded (badly) like this:

foreach(PropertyInfo info in typeof(BusinessEntity).GetProperties())
{
  if(info.PropertyType is GenericIList &&
     TheNestedTypeInThisList.IsAssignableFrom(IEntityBase)
  {
    return true;
  }
}

Only option I've heard so far, that works, would be to pull out the first item from that list, then look at its type. Any easier way (especially because I can't be guaranteed that the List won't be empty)?

like image 822
joshua.ewer Avatar asked Feb 11 '09 18:02

joshua.ewer


1 Answers

Assuming you have the System.Type which describes your List<>, you can use the Type.GetGenericArguments() method to get the Type instance which describes what it's a list of.

like image 50
ChrisW Avatar answered Oct 03 '22 22:10

ChrisW