Wednesday, April 6, 2011

HOW TO: Get contained type in a Generic List 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)?

From stackoverflow
  • 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.

  • something like this?

            foreach (System.Reflection.PropertyInfo info in typeof(BusinessEntity).GetProperties())
            {
                if (info.PropertyType.IsGenericType &&
                    info.PropertyType.Name.StartsWith("IList") &&
                    info.PropertyType.GetGenericArguments().Length > 0 &&
                        info.PropertyType.GetGenericArguments()[0] == typeof(string)
                    )
                {
                    return true;
                }
            }
    

0 comments:

Post a Comment