is there a way to retrieve type T
from IEnumerable<T>
through reflection?
e.g.
i have a variable IEnumerable<Child>
info; i want to retrieve Child's type through reflection
IEnumerable<T> is the base interface for collections in the System. Collections. Generic namespace such as List<T>, Dictionary<TKey,TValue>, and Stack<T> and other generic collections such as ObservableCollection<T> and ConcurrentStack<T>.
var item = eLevelData. ElementAt(index); If your collection is typed as IEnumerable instead of IEnumerable<T> you'll need to use the Cast extension method before you can call ElementAt e.g.
IEnumerable has just one method called GetEnumerator. This method returns another type which is an interface that interface is IEnumerator. If we want to implement enumerator logic in any collection class, it needs to implement IEnumerable interface (either generic or non-generic).
IEnumerable<T> myEnumerable; Type type = myEnumerable.GetType().GetGenericArguments()[0];
Thusly,
IEnumerable<string> strings = new List<string>(); Console.WriteLine(strings.GetType().GetGenericArguments()[0]);
prints System.String
.
See MSDN for Type.GetGenericArguments
.
Edit: I believe this will address the concerns in the comments:
// returns an enumeration of T where o : IEnumerable<T> public IEnumerable<Type> GetGenericIEnumerables(object o) { return o.GetType() .GetInterfaces() .Where(t => t.IsGenericType && t.GetGenericTypeDefinition() == typeof(IEnumerable<>)) .Select(t => t.GetGenericArguments()[0]); }
Some objects implement more than one generic IEnumerable
so it is necessary to return an enumeration of them.
Edit: Although, I have to say, it's a terrible idea for a class to implement IEnumerable<T>
for more than one T
.
I'd just make an extension method. This worked with everything I threw at it.
public static Type GetItemType<T>(this IEnumerable<T> enumerable) { return typeof(T); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With