mercredi 12 avril 2017

How do I get the type of a generic parameter on IEnumerable

I created a method to tell me what the Type of the object in an generic IEnumerable is. It seemed like a straightforward affair but I got unexpected results when I tried passing the value collection from a Dictionary to my method. I would like to know how to fix the method to return the right result and ideally I would also like an explanation of why I get the results that I get.

//sample class (target type to get)
public class Person
{
    public string Name { get; set; }    
    public int Age { get; set; }
}

//method that extracts the type
public Type GetItemType(IEnumerable<object> collection)
{
    Type collectionType = collection.GetType();
    Type[] genericArguments = collectionType.GetGenericArguments();
    return genericArguments[0];
}

//sample data for test
var folk = new Dictionary<string, Person>();
folk.Add("Joe", new Person() { Name="Joseph Stalin", Age = 43 });
folk.Add("Tony", new Person() { Name="Winston Churchill", Age = 65 });

IEnumerable<Person> people = folk.Values;
Type itemType = GetItemType(people);

The itemType is "System.String" and not "Person". It seems to take the type generic parameters from the actual Dictionary and not the values collection.





Aucun commentaire:

Enregistrer un commentaire