Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find the type of T in a c# Generic collection of T when all I know is the type of the collection?

Tags:

c#

.net

generics

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
    }
}
like image 701
Jason Avatar asked Sep 02 '11 12:09

Jason


1 Answers

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 :)

like image 140
Jon Skeet Avatar answered Oct 06 '22 11:10

Jon Skeet