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?
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
}
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