List vs IEnumerable – Why Use List?

asp.net-mvcentity-frameworknetprogramming practices

In my ASP.net MVC4 web application I use IEnumerables, trying to follow the mantra to program to the interface, not the implementation.

Return IEnumerable(Of Student)

vs

Return New List(Of Student)

People are telling me to use List and not IEnumerable, because lists force the query to be executed and IEumerable does not.

Is this really best practice? Is there any alternative? I feel strange using concrete objects where an interface could be used. Is my strange feeling justified?

Best Answer

There are times when doing a ToList() on your linq queries can be important to ensure your queries execute at the time and in the order that you expect them to. Those scenarios are however rare and nothing one should worry too much about until they genuinely run into them.

Long story short, use IEnumerable anytime you only need iteration, use IList when you need to index directly and need a dynamically sized array (if you need indexing on a fixed size array then just use a standard array).

As for the execution time thing, you can always use a list as an IEnumerable variable, so feel free to return an IEnumerable by doing a .ToList();, or pass in a parameter as an IEnumerable by executing .ToList() on the IEnumerable to force execution right then and there. Just be careful that anytime you force execution with .ToList() you don't hang on to the IEnumerable variable which you just did that to and execute it again, or else you'll end up doubling the iterations in your LINQ query unnecessarily.

In regards to MVC, there is really nothing special to note here. It's going to follow the same execution time rules as the rest of .NET, I think you might have someone who was bit by confusion caused by the delayed execution semantics in the past and blamed it on MVC telling you this is somehow related, but it's not. The delayed execution semantics confuse everybody at first (and even for a good while afterwards; they can be a touch tricky). Again though, just don't worry about it until you really care about ensuring a LINQ query doesn't get executed twice or require it executed in a certain order relative to other code, at which point assign your variable to itself.ToList() to force execution and you'll be fine.