Is there a general way to detect if a property's type is an enumerable type?

Viewed 22573

Given this:

class InvoiceHeader {
    public int InvoiceHeaderId { get; set; }
    IList<InvoiceDetail> LineItems { get; set; }
}

I'm currently using this code to detect if a class has a collection property:

void DetectCollection(object modelSource)
{       
    Type modelSourceType = modelSource.GetType();
    foreach (PropertyInfo p in modelSourceType.GetProperties())
    {
        if (p.PropertyType.IsGenericType &&  p.PropertyType.GetGenericTypeDefinition() == typeof(IList<>))
        {
            System.Windows.Forms.MessageBox.Show(p.Name);
        }
    }
}

Is there a general way to detect if the LineItems is an enumerable type? Some will use other enumerable type (e.g. ICollection), not an IList.

4 Answers
p.PropertyType.IsGenericType
    && p.PropertyType.GetGenericTypeDefinition().Equals(typeof(ICollection<>))

This worked for me when using Entity Framework context.

Related