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 with GetGenericArguments
:
if (typeOfProperty.IsGenericype)
{
Type genericDefinition = typeOfProperty.GetGenericTypeDefinition();
if (genericDefinition == typeof(ICollection<>)
{
// Note that we're calling GetGenericArguments on typeOfProperty,
// not genericDefinition.
Type typeArgument = typeOfProperty.GetGenericArguments()[0];
// typeArgument is now the type you want...
}
}
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 :)
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