If you need to find out what kind of object is the "Item" in a generic collection (e.g. System.Collections.Generic.List<Monkey> would give "Monkey")
Code:/// <summary> /// Gets the item type used in any type-safe generic list /// or generic list derived class... /// </summary> /// <param name="genericType"> /// The collection type /// </param> /// <returns></returns> public static Type GetItemTypeFromGenericType(Type genericType) { if (genericType.IsGenericType) { Type[] genericTypes = genericType.GetGenericArguments(); if (genericTypes.GetUpperBound(0) >= 0) { return genericTypes[genericTypes.GetUpperBound(0)]; } else { return null; } } else { if (genericType.BaseType != null) { return GetItemTypeFromGenericType(genericType.BaseType); } else { return null; } } }




Reply With Quote