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.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With