tags:

views:

50

answers:

2

Below is some code I use to get the initial state of all public properties in a class for IsDirty checking.

What's the easiest way to see if a property is IEnumerable?

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);
    }
+5  A: 
if ( typeof( IEnumerable ).IsAssignableFrom( pi.PropertyType ) )
Fyodor Soikin
A: 

Try

private bool IsEnumerable(PropertyInfo pi)
{
   return pi.PropertyType.IsSubClassOf(typeof(IEnumerable));
}
Steve Danner
I recently noticed that `x.IsSubClassOf(y)` will return false if x == y. In this situation, if the property happened to actually be of type `IEnumerable`, then the function would return false.
Dr. Wily's Apprentice
That is interesting, I've honestly never actually used this logic in this exact context, so I'm glad you pointed that out. Thanks.
Steve Danner