Search code examples
generics.net-4.0typeinfo

.Net How to compare generic typeinfo


I want to filter a collection of properties to find all properties that are of type EntityCollection<> like so:

entity.GetProperties().Where(p => p.PropertyType == typeof(EntityCollection<>));

The above code will always return no results because the properties will be of type EntityCollection<TEntity> where TEntity is an EntityObject.

I've also tried using EntityCollection<EntityObject> with no success.

I don't care about the specific type of TEntity, I just want properties that are of type EntityCollection<> regardless of the type of TEntity.

This seems like it should be simple, am I missing a trick here? :-)


Solution

  • Well, you could use:

    Where(p => p.PropertyType.IsGenericType && 
               p.PropertyType.GetGenericTypeDefinition() == typeof(EntityCollection<>))
    

    Is that what you're after? Note that this won't find subtypes of EntityCollection<TEntity>.