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)?
Assuming you have the
System.Typewhich describes yourList<>, you can use theType.GetGenericArguments()method to get theTypeinstance which describes what it’s a list of.