On my current project I had the need to iterate through the properties of an object with reflection and to check if one of the properties is a generic List type, e.g. IList<int>, IList<Customer>, etc. To check through reflection on a generic type, you need to use the GetGenericTypeDefinition method.
foreach (PropertyInfo propertyInfo in entity.GetType().GetProperties()) { if (propertyInfo.PropertyType.IsGenericType && typeof(List<>).IsAssignableFrom(propertyInfo.PropertyType.GetGenericTypeDefinition())) { IEnumerable enumerable = propertyInfo.GetValue(entity, null) as IEnumerable; IEnumerator enumerator = enumerable.GetEnumerator(); while (enumerator.MoveNext()) { // do something } } }
Remember Me
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.