Let say I have a generic member in a class or method, so:
public class Foo
{
public List Bar { get; set; }
public void Baz()
{
You can get the type of "T" from any collection type that implements IEnumerable
public static Type GetCollectionItemType(Type collectionType)
{
var types = collectionType.GetInterfaces()
.Where(x => x.IsGenericType
&& x.GetGenericTypeDefinition() == typeof(IEnumerable<>))
.ToArray();
// Only support collections that implement IEnumerable once.
return types.Length == 1 ? types[0].GetGenericArguments()[0] : null;
}
Note that it doesn't support collection types that implement IEnumerable
public class WierdCustomType : IEnumerable, IEnumerable { ... }
I suppose you could return an array of types if you needed to support this...
Also, you might also want to cache the result per collection type if you're doing this a lot (e.g. in a loop).