24

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?

  • 2
    Er, first, why is it a good thing to force the query to be executed? Second, you should be monitoring and profiling the database calls to evaluate whether this technical consideration has any merit. – user16764 Apr 6 '13 at 3:34
  • 2
    It's said that all queries should be executed so that the model is done and loaded ready for the view. I.e. the view should receive everything and not be querying the database. – Rowan Freeman Apr 6 '13 at 3:36
  • 3
    This StackOverflow question covers it pretty well. – Karl Bielefeldt Apr 6 '13 at 3:47
  • That is a good answer, but I want to know it's relevance to MVC. Why can't the view be given IEnumerables so that all queries run just-in-time? – Rowan Freeman Apr 6 '13 at 3:51
  • 2
    "It's said that all queries should be executed so that the model is done and loaded ready for the view. I.e. the view should receive everything and not be querying the database.". That's nonsense. If you pass an IEnumerable, then your view doesn't know or care whether it's querying the database. And that's the way it should be. – user16764 Apr 6 '13 at 16:30
21

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.

  • Is it bad to give a view IEnumerables? Should you give it Lists so that the queries have been executed by the time the view gets them? – Rowan Freeman Apr 6 '13 at 3:54
  • @RowanFreeman I just added an edit to answer this. I think you've got someone who ran into something they didn't entirely understand (can't blame them, delayed execution is seriously complex and confusing) and chalked it up to bad joojoo instead of working to understand the full behaviour of delayed execution semantics. – Jimmy Hoffa Apr 6 '13 at 3:57
  • Nice answer. So will I ever actually need to use .ToList()? So far my application works fine using only IEnumerables and passing them from the model to the view. No List or .ToList(). My question isn't one of functionality - I know my application works. My question is one of best-practice. – Rowan Freeman Apr 6 '13 at 4:00
  • 4
    @RowanFreeman best practice is to use the minimal interface that still meets your requirements. IEnumerable is doing this right now for you so don't worry about changing it. That said, a day will come when you'll have a query executing 3 or 10 times and not understand why, or expecting a query to execute before an insert only to find it executes afterwards, these are the times you need to recognize .ToList() will force execution when you want, and reiterating an IEnumerable from a LINQ query multiple times will execute the whole query multiple times; Fix your execution when those events happen – Jimmy Hoffa Apr 6 '13 at 4:04
  • 1
    You shouldn't even use List--passing around a List implies that the contents of the list are going to be modified. If you want to return a collection, use IReadOnlyCollection. List is for use within methods, and for exchange between methods that modify the list. That's it! – ErikE Feb 11 '16 at 21:18
7

There are two issues.

IENumerable<Data> query = MyQuery();

//Later
foreach (Data item in query) {
  //Process data
}

By the time the "Process Data" loop is reached, the query may no longer by valid. For example, if the query is being run on a DataContext that has already been Disposed, your code will throw an exception. This kind of thing becomes very confusing when you are processing a query in a different context than where you created it.

A secondary issue is that your connection will not be released until the "Process Data" loop completes. This is only a problem if "Process Data" is complex. This is mentioned at http://msdn.microsoft.com/en-us/library/bb386929.aspx :

Q. How long does my database connection remain open?

A. A connection typically remains open until you consume the query results. If you expect to take time to process all the results and are not opposed to caching the results, apply ToList to the query. In common scenarios where each object is processed only one time, the streaming model is superior in both DataReader and LINQ to SQL.

So, these issues are why you are being encouraged to ensure that the query is actually executed, e.g. by calling ToList(). However, as Jimmy Suggests there is nothing stopping you from returning your List as an IEnumerable .

As a general rule, I recommend avoiding iterating over an IEnumerable more than once. Assuming consumers of your code follow this rule, I don't consider it a concern that someone might hit the database twice by executing the query twice.

1

Another benefit of enumerating the IEnumerable early is exceptions will be thrown at the appropriate location. This assists debugging.

For example, if you got a deadlock exception inside one of your Razor views, it wouldn't really be as clear as if the exception occurred during one of your data access methods.

  • Any method returning an IEnumerable that can throw is probably making a mistake. Deferred IEnumerable methods should be split into two: one non-deferred method checks parameters and sets up, throwing if necessary (say, because of a null argument). Then it returns a call to the private implementation which is deferred. I don't think my comments are completely at odds with your answer, but do think that you've left out an important aspect in your answer, which is the semantic meaning of using IEnumerable vs. a List (mutation) vs. IReadOnlyCollection (no benefit to deferral). – ErikE Feb 11 '16 at 21:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.