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