4

I have an object that contains some ICollection type properties

So basically the class looks like this:

Class Employee {

public ICollection<Address> Addresses {get;set;}

public ICollection<Performance> Performances {get; set;}

}

The problem is get property names of type ICollection, inside of Generic class, by using reflection.

My Generic Class is

Class CRUD<TEntity>  {

public object Get() {
 var properties = typeof(TEntity).GetProperties().Where(m=m.GetType() == typeof(ICollection ) ... 
}

But it is not working.

How can I get a property here?

codebased
  • 6,945
  • 9
  • 50
  • 84

2 Answers2

8

GetProperties() returns a PropertyInfo[]. You then do a Where using m.GetType(). If we assume that you missed a >, and this is m=>m.GetType(), then you are actually saying:

 typeof(PropertyInfo) == typeof(ICollection)

(caveat: actually, it is probably a RuntimePropertyInfo, etc)

What you mean is probably:

typeof(ICollection).IsAssignableFrom(m.PropertyType)

However! Note that ICollection <> ICollection<> <> ICollection<Address> etc - so it isn't even that easy. You might need:

m.PropertyType.IsGenericType &&
    m.PropertyType.GetGenericTypeDefinition() == typeof(ICollection<>)

Confirmed; this works:

static void Main()
{
    Foo<Employee>();
}
static void Foo<TEntity>() {
    var properties = typeof(TEntity).GetProperties().Where(m =>
        m.PropertyType.IsGenericType &&
        m.PropertyType.GetGenericTypeDefinition() == typeof(ICollection<>)
    ).ToArray();
    // ^^^ contains Addresses and Performances
}
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • Thank you Marc, it works! Yes indeed I was getting RuntimePropertyInfo and I did exactly what you did but I don't know why it is different and probably because I was comparing with ICollection! – codebased Jul 30 '14 at 11:28
2

You can use IsGenericType and check GetGenericTypeDefinition against typeof(ICollection<>)

public object Get()
{
    var properties =
        typeof (TEntity).GetProperties()
            .Where(m => m.PropertyType.IsGenericType && 
                    m.PropertyType.GetGenericTypeDefinition() == typeof (ICollection<>));
}
Sriram Sakthivel
  • 72,067
  • 7
  • 111
  • 189