I keep hearing that in .net 3.5 you should use IEnumerable over a List, but I can’t find any reference materials or articles that explain why it’s so much more proficient. Does anyone know of any content that explains this?
The purpose of asking this question is to get a better understanding of what IEnumerable is doing under the hood. If you can provide me with any links I will do the research and post an answer.
IEnumerable<T>is an interface that is implemented byList<T>. I suspect the reason you’re hearing thatIEnumerable<T>should be used is because it’s a less constrictive interface requirement.For example, consider the following method signature:
This method requires that it be passed a concrete implementation of a List. But it’s just doing something in-order. It doesn’t really need random access or any of the other things that a
List<T>or even anIList<T>give it. Instead, the method should accept anIEnumerable<T>:Now we’re using the most general (least specific) interface that supports the operations that we need. This is a fundamental aspect of OO-design. We’ve decreased coupling by requiring only what we need, and not a whole lot else besides. We’ve also created a more flexible method because the
foosparameter might be aQueue<T>, aList<T>, anything that implementsIEnumerable<T>. 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 thatIEnumerable<T>is a more efficient design construct because it’s a more specific indication of what your design requires. (Though this can lead to runtime gains in specific cases.)