Reputation: 7073
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?
Upvotes: 4
Views: 2416
Reputation: 73492
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<>));
}
Upvotes: 2
Reputation: 1063599
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
}
Upvotes: 8