Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Relation between List<> and IEnumerable<> open type

Tags:

Is there any relationship between the open types List<> and IEnumerable<>?

Example:

var type1 = typeof(List<>); var type2 = typeof(IEnumerable<>);  //return false type2.IsAssignableFrom(type1); 

Is there any method to check the relationship between two open type, or the relationship only exist on closed type?

like image 712
YonF Avatar asked Nov 20 '18 07:11

YonF


People also ask

What is the difference between IEnumerable and List?

IEnumerable is a deferred execution while List is an immediate execution. IEnumerable will not execute the query until you enumerate over the data, whereas List will execute the query as soon as it's called. Deferred execution makes IEnumerable faster because it only gets the data when needed.

Why we use IEnumerable instead of List?

We aren't forcing the caller to convert their data structure to a List unnecessarily. So it isn't that IEnumerable<T> is more efficient than list in a "performance" or "runtime" aspect. It's that IEnumerable<T> is a more efficient design construct because it's a more specific indication of what your design requires.

Does List implement IEnumerable?

List implements IEnumerable, but represents the entire collection in memory. LINQ expressions return an enumeration, and by default the expression executes when you iterate through it using a foreach, but you can force it to iterate sooner using .

Is IEnumerable faster than List?

1) if you iterate elements from IEnumerable or List only one time, so both are same, no differences. 2) if you iterate elements many times, or if you get an one element for multiple times, so, IEnumerable will be slow.


1 Answers

List<> and IEnumerable<> are not types; they are type definitions. As such it doesn't really make sense to ask if one is assignable to the other. Neither can be assigned to. You can't declare a variable List<> a = null, for example-- you will get a compilation error "Unexpected use of an unbound generic name."

A type definition becomes a generic type when you specify the type parameter. At that point, it is a type and can be assigned to. So for example List<string> can be assigned to IEnumerable<string>.

If you have a type definition in mind and you want to do a type-compatibility check, just use <object> (or a suitable type if there is a type constraint) instead of <>:

var type1 = typeof(List<object>); var type2 = typeof(IEnumerable<object>);  //returns true type2.IsAssignableFrom(type1); 
like image 90
John Wu Avatar answered Sep 20 '22 03:09

John Wu