Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting type T from IEnumerable<T>

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

like image 796
Usman Masood Avatar asked May 25 '09 12:05

Usman Masood


People also ask

What is IEnumerable T?

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>.

How do I access items in IEnumerable?

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.

What is IEnumerable return type?

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).


2 Answers

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.

like image 189
jason Avatar answered Oct 26 '22 18:10

jason


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); } 
like image 26
amsprich Avatar answered Oct 26 '22 20:10

amsprich