Search code examples
c#genericscollectionspropertyinfo

How would I know if a property is a generic collection


I need to know if the type of a property in a class is a generic collection (List, ObservableCollection) using the PropertyInfo class.

foreach (PropertyInfo p in (o.GetType()).GetProperties())
{
    if(p is Collection<T> ????? )

}

Solution

  • GetGenericTypeDefinition and typeof(Collection<>) will do the job:

    if(p.PropertyType.IsGenericType && typeof(Collection<>).IsAssignableFrom(p.PropertyType.GetGenericTypeDefinition())