Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the type contained in a collection through reflection

In some part of my code I am passed a collection of objects of type T. I don't know which concrete colletion I will be passed, other than it impements IEnumerable.

At run time, I need to find out which type T is (e.g. System.Double, System.String, etc...).

Is there any way to find it out?

UPDATE: I should maybe clarify a bit more the context I am working in (a Linq Provider).

My function has a signature like the following, where I get the type of the collection as a parameter:

string GetSymbolForType(Type collectionType)
{

}

Is there any way from collectionType to get the contained objects type?

like image 714
Stefano Ricciardi Avatar asked Dec 14 '09 11:12

Stefano Ricciardi


2 Answers

myCollection.GetType().GetGenericArguments() 

will return an array of the type args.

like image 195
nitzmahone Avatar answered Oct 11 '22 13:10

nitzmahone


From Matt Warren's Blog:

internal static class TypeSystem {
    internal static Type GetElementType(Type seqType) {
        Type ienum = FindIEnumerable(seqType);
        if (ienum == null) return seqType;
        return ienum.GetGenericArguments()[0];
    }
    private static Type FindIEnumerable(Type seqType) {
        if (seqType == null || seqType == typeof(string))
            return null;
        if (seqType.IsArray)
            return typeof(IEnumerable<>).MakeGenericType(seqType.GetElementType());
        if (seqType.IsGenericType) {
            foreach (Type arg in seqType.GetGenericArguments()) {
                Type ienum = typeof(IEnumerable<>).MakeGenericType(arg);
                if (ienum.IsAssignableFrom(seqType)) {
                    return ienum;
                }
            }
        }
        Type[] ifaces = seqType.GetInterfaces();
        if (ifaces != null && ifaces.Length > 0) {
            foreach (Type iface in ifaces) {
                Type ienum = FindIEnumerable(iface);
                if (ienum != null) return ienum;
            }
        }
        if (seqType.BaseType != null && seqType.BaseType != typeof(object)) {
            return FindIEnumerable(seqType.BaseType);
        }
        return null;
    }
}
like image 36
dtb Avatar answered Oct 11 '22 12:10

dtb