How to find out if PropertyInfo is a collection

Below is the code that I use to get the initial state of all public properties in the class to check for IsDirty.

What is the easiest way to see if an IEnumerable property is?

Cheers
Berryl

protected virtual Dictionary<string, object> _GetPropertyValues() { return _getPublicPropertiesWithSetters() .ToDictionary(pi => pi.Name, pi => pi.GetValue(this, null)); } private IEnumerable<PropertyInfo> _getPublicPropertiesWithSetters() { return GetType().GetProperties().Where(pi => pi.CanWrite); } 

UPDATE

What I did was add a few library extensions, as shown below.

  public static bool IsNonStringEnumerable(this PropertyInfo pi) { return pi != null && pi.PropertyType.IsNonStringEnumerable(); } public static bool IsNonStringEnumerable(this object instance) { return instance != null && instance.GetType().IsNonStringEnumerable(); } public static bool IsNonStringEnumerable(this Type type) { if (type == null || type == typeof(string)) return false; return typeof(IEnumerable).IsAssignableFrom(type); } 
+29
reflection c #
Aug 25 '10 at 20:08
source share
3 answers
 if ( typeof( IEnumerable ).IsAssignableFrom( pi.PropertyType ) ) 
+37
Aug 25 '10 at 20:12
source share

I agree with Fyodor Soikin, but the fact that Enumerable does not mean that it is just a collection, since the string is also enumerable and returns characters one by one ...

Therefore, I suggest using

 if (typeof(ICollection<>).IsAssignableFrom(pi.PropertyType)) 
+11
Mar 15 '13 at 11:49
source share

Try

 private bool IsEnumerable(PropertyInfo pi) { return pi.PropertyType.IsSubclassOf(typeof(IEnumerable)); } 
+1
Aug 25 '10 at 20:12
source share



All Articles