views:

116

answers:

1

I am attempting to use Reflection in C# to determine at runtime the type of objects in a collection property. These objects are entities generated by the Entity Framework:

Type t = entity.GetType();
PropertyInfo [] propInfo = t.GetProperties();
foreach(PropertyInfo pi in propInfo)
{
    if (pi.PropertyType.IsGenericType)
    {
        if (pi.PropertyType.GetGenericTypeDefinition() 
            == typeof(EntityCollection<>))   
        //  'ToString().Contains("EntityCollection"))'  removed d2 TimWi's advice
        //
        //  --->  this is where I need to get the underlying type
        //  --->  of the objects in the collection :-)
        // etc.
    }
}

How do I identify the type of objects held by the collection?

EDIT: updated code above, adding first .IsGenericType query to make it work

+2  A: 

You can use GetGenericArguments() to retrieve the generic arguments of the collection type (for example, for EntityCollection<string>, the generic argument is string). Since EntityCollection<> always has one generic argument, GetGenericArguments() will always return a single-element array, so you can safely retrieve the first element of that array:

if (pi.PropertyType.IsGeneric &&
    pi.PropertyType.GetGenericTypeDefinition() == typeof(EntityCollection<>))
{
    // This is now safe
    var elementType = pi.PropertyType.GetGenericArguments()[0];

    // ...
}
Timwi
item[0]? Do you mean the "GetGenericArguments()"? That would not be empty.
Kirk Woll
Good point Kirk, corrected.I misunderstood the code to be querying the [0] element of the collection of entity objects (which could have been empty) vs. querying the [0] element of GenericArguments.
Jay
Thanks Timwi. The only problem is that an exception is thrown if the property isn't a generic type. I updated my question with your suggestions and the additional "if (pi.PropertyType.IsGenericType)" line.
Jay
Good point! I’ll fix :)
Timwi