Why return ienumerable instead of list




















Just make it clear. IEnumerable has the dual purpose of having lazy-evaluation semantics but also being a immutable structure to users. But if you want a proper readonly collection return a proper immutable list.

I try and avoid IList because ultimately I felt uncomfortable with the result being modified afterwards. IEnumerable for the lazy methods makes perfect sense. See also immutable list msdn. Show 2 more comments. Active Oldest Votes. Edit - To address your "Update 1": If you are really concerned, you might add some information into the documentation, but I don't think it's necessary. Improve this answer. Ocelot20 Ocelot20 1, 9 9 silver badges 18 18 bronze badges. I'm just bothered by the defered execution of the enumerable..

But still, it's a great answer. I am saying "don't assume you know better than the caller by forcing them to use List unless the intended use of the method is always need indexed access, etc. Does it make more sense? Dan Dan 3, 20 20 silver badges 39 39 bronze badges. There are plenty of perfectly acceptable reasons to return a lazily evaluated IEnumerable from a db. It all comes down to what that individual class claims to be responsible for.

Also, "you have no guarantee the connection will be alive" is a concern of the class returning the IEnumerable , not the caller. If he is, then he will run into concurrency issues if he does not ToList the enumerable, and I am only saying that out of pain born from doing exactly the opposite. I did point out though that if you can bind the lifetime of the resource to the IEnumerable that this is circumvented.

But I would say that having a lazily evaluated structure coming straight from the DB layer and leaving the DB layer is likely to be a bad thing if it talks directly to the database connection. As I mentioned, certainly in Ef, you will run into a lot of problems by doing this. I guess I meant "overly generalized statement". Like I mentioned before, there are plenty of acceptable reasons to return a lazily evaluated IEnumerable from a db, but without seeing more code we can't really say what problems he'll run into.

It's certainly a potential problem worth mention though. It does sound like one to look into. Do you have any ideas how it could be implemented? Show 1 more comment. Community Bot 1. The number of times the method is called, as well as whether or not the consumer iterates over the result would be the determining factor. Sign up or log in Sign up using Google.

Sign up using Facebook. Sign up using Email and Password. Post as a guest Name. Well, if client only wants to access the objects, it can just awkwardly append. ToList to the end of each call to the method and have exactly what it wants. If the client wants to modify the state of the grouping e.

What about the flip side? If the client really wants an IEnumerable and you give them a list? Most likely they want IEnumerable for deferred execution purposes, and you will fail at that. At the broadest level, you should ask yourself what your client is going to be doing with the thing that you return and try to accommodate that.

Think of what needs to be done, and then go looking for the data type that represents the smallest superset of those things or, write your own, if nothing seems to fit. This is especially true if there is no interface seem between the collaborating components. Another thing that I do is try to minimize the amount of collections that I pass around an application.

But in other places, I try to make aggregation an internal implementation detail to a class. Command-Query Separation helps with this.

And finally, when in doubt and all else seems to be a toss-up, I tend to favor promising the least thus favoring future flexibility. Unless you want your client to modify your internal list, I would pretty much never advocate returning an IList.

An IList on an interface implies foo. Add x works. If you are not intending them to mutate your state via a reference to your list, but they simply want to mutate their own copy, then it should be up to them to convert the IEnumerable into mutable version in the local context. Count … Read more ». I wondered if your point might be too obvious of a bad practice for the Internet at large to benefit from hearing, but I do know of a team with some people who could benefit from one more chance to learn that lesson.

Would you please refill this for me? I bet that would actually be pretty helpful and indicative of sophistication off the top, you could have a scheme where you inherited the interface and did ILazyEnumerable and IMaterializedEnumrable. But yeah, coughing up internal guts that bit me at times when I was junior developer and was a big reason I gravitated away returning modifiable collections that I needed or exposing them as properties. Any ,. Count to.

ElementAt are valid without concern. Returning the least derived type IEnumerable will leave you the most leeway to change the underlying implementation down the track. Returning a more derived type IList provides the users of your API with more operations on the result. I would always suggest returning the least derived type that has all the operations your users are going to need ToList before you return from your method means that your items may be iterated twice - once to create the List, and once when the caller loops through, filters, or transforms your return value.

If my caller needs a List, that's a single easy method call away - I don't need to make that decision for them, and that makes my code slightly more efficient in the cases where the caller is just doing a foreach. So the question boils down to: in your application's specific use case, do you WANT to support such uses presumably by returning a freshly constructed collection! Only you can answer this question, and only by understanding well what your callers will want to do with the return value, and how important performance is here how big are the collections you would be copying, how likely is this to be a bottleneck, etc.

It's not so simple when you are talking about return values instead of input parameters. When it's an input parameter, you know exactly what you need to do. So, if you need to be able to iterate over the collection, you take an IEnumberable whereas if you need to add or remove, you take an IList. In the case of a return value, it's tougher. What does your caller expect? If you return an IEnumerable, then he will not know a priori that he can make an IList out of it.

But, if you return an IList, he will know that he can iterate over it. So, you have to take into account what your caller is going to do with the data.

I think you can use either, but each has a use. Basically List is IEnumerable but you have count functionality, add element, remove element. If the collection is intended to be readonly, or the modification of the collection is controlled by the Parent then returning an IList just for Count is not a good idea. Count if the underlying type is of IList , so performance difference is negligible.

Generally I feel opinion it is better practice to return IEnumerable where possible, if you need to do additions then add these methods to the parent class, otherwise the consumer is then managing the collection within Model which violates the principles, e.

Add model violates law of demeter. Of course these are just guidelines and not hard and fast rules, but until you have full grasps of applicability, following blindly is better than not following at all. Returning IList my votes are always againist it but it's mainly what you like and what not. If you do not counting in your external code it is always better to return IEnumerable, because later you can change your implementation without external code impact , for example, for yield iterator logic and conserve memory resources very good language feature by the way.

However if you need items count, don't forget that there is another layer between IEnumerable and IList - ICollection. They all implement IEnumerable , but that sounds to me a bit too low-level for the job. Basically List is IEnumerable but you have count functionality, Add element, remove element. IEnumerable is not efficient for counting elements, or getting a specific element in the collection. List is a collection which is ideally suited to finding specific elements, easy to add elements, or remove them.

I think the general rule is to use the more specific class to return, to avoid doing unneeded work and give your caller more options. That said, I think it's more important to consider the code in front of you which you are writing than the code the next guy will write within reason.

This is because you can make assumptions about the code that already exists. Remember that moving UP to a collection from IEnumerable in an interface will work, moving down to IEnumerable from a collection will break existing code.

What you get as far as a pizza and its toppings is determined by how you "type" your list when you create its object reference in memory. You have to declare the type of pizza you are cooking as follows:. Note you cannot instantiate an Interface as itself or eat raw pepperoni. NET Library has implemented all the other Interfaces!! But you might not need everything. Choosing one Interface type allows your application to store a smaller object with less members and keeps your application tight.

Who needs Supreme Pizza every time? But there is a second reason for using Interface types: Flexibility. Because other types in. Dependency Injection is a good example of this type of flexibility using Interfaces rather than concrete types, and why you might want to create objects using Interfaces. Stack Overflow for Teams — Collaborate and share knowledge with a private group.

Create a free Team What is Teams? Collectives on Stack Overflow.



0コメント

  • 1000 / 1000