Looping through properties of a generic type T
, I'd like to know if T
happens to be a List
then what type of items does that list contain.
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
foreach (PropertyDescriptor prop in properties)
if (prop.PropertyType.Name.Equals("List`1"))
???
I can detect if type is a List
using the above code but then how can I get the type of list items?
You can get the generic arguments use GetGenericArguments
method, it will return an array of types, you can just get the first type which is the type of generic argument of your list:
var type = prop.PropertyType.GetGenericArguments()[0];
Also instead of comparing names to check property type I would suggest this way:
if(prop.PropertyType.IsGenericType &&
prop.PropertyType.GetGenericTypeDefinition() == typeof(List<>))