I have an array of PropertyInfo representing the properties in a class. Some of these properties are of type ICollection<T>, but T varies across the properties – I have some ICollection<string>, some ICollection<int>, etc.
I can easily identify which of the properties are of type ICollection<> by using the GetGenericTypeDefinition() method on type, but I am finding it impossible to get the type of T – the int or string in my example above.
Is there a way to do this?
IDocument item
PropertyInfo[] documentProperties = item.GetType().GetProperties();
PropertyInfo property = documentProperties.First();
Type typeOfProperty = property.PropertyType;
if (typeOfProperty.IsGenericType)
{
Type typeOfProperty = property.PropertyType.GetGenericTypeDefinition();
if (typeOfProperty == typeof(ICollection<>)
{
// find out the type of T of the ICollection<T>
// and act accordingly
}
}
If you know it’ll be
ICollection<X>but don’t know X, that’s fairly easy withGetGenericArguments:It gets harder when the type is some type which implements
ICollection<T>but may itself be generic. It sounds like you’re in a better position 🙂