Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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.

like image 795
Hao Avatar asked Jun 26 '11 09:06

Hao


People also ask

How do you check if property is of type is a class?

Examples. The following example creates an instance of a type and indicates whether the type is a class. type MyDemoClass = class end try let myType = typeof<MyDemoClass> // Get and display the 'IsClass' property of the 'MyDemoClass' instance. printfn $"\nIs the specified type a class? {myType.


1 Answers

Your code doesn't actually check if the properties are Enumerable types but if they are generic IList's. Try this:

if(typeof(IEnumerable).IsAssignableFrom(p.PropertyType)) {    System.Windows.Forms.MessageBox.Show(p.Name); } 

Or this

if (p.PropertyType.GetInterfaces().Contains(typeof(IEnumerable))) {     System.Windows.Forms.MessageBox.Show(p.Name); } 
like image 76
Magnus Avatar answered Sep 23 '22 03:09

Magnus