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.
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.
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With