开发者

Why is it preferred to use IEnumerable<T> to List<T>

I have been hearing that it is important to use the lowest class possible when passing parameters to m开发者_如何转开发ethods. Why is this? Also where can i find more information on what the class hierarchy is? I would like to know what IEnumerable inheriated from and so forth.


If you use IEnumerable<T> as a parameter type, then you can pass in any type that implements that interface. That includes List<T>, Stack<T>, Queue<T>, etc.

It also includes various anonymous types that might be the result of a LINQ query, and also the very important IQueryable<T>.


By using "low-level" arguments, you give your method the ability to work on a larger variety of objects. It encourages writing generic re-usable methods.

MSDN can tell you what different things inherit from (in the case of IEnumerable, it inherits from nothing, because it represents pretty much the most primitive idea of a "list")


IEnumerable is a read-only sequence, while a List can be appended to.

If you design your public API so that it exposes IList<T> all over the place and then realize that you want to return a read only list, you have to either break your code by changing to IEnumerable<T> or use the horrible ReadOnlyCollection. I call it horrible because it throws exceptions on .Add/.Remove etc.

So if you only need to read, return IEnumerable, if your callers need to add/append, return IList.

On another note: Never return a List<T>, always an IList<T>. The reason is that List is a concrete class that can't be overridden in any sensible way, while IList is an interface that allows you to change the actual implementation without breaking the public contract.


The quickest thing I can think of is this: what happens if you no longer want your implementation to be of type List<T>?

Let's say you one day decide to refactor your application to use a LinkedList<T> or a SortedList<T>, all you have to change is that type instead of all of the types in all of the methods you might be passing your collection around to.

You can improve the maintainability of your code by using this technique.


The idea is to maximize the flexibility of your function. If you require a List<T>, then callers must have one to pass in. If they don't have one handy, they'll have to create one, and this is expensive. If you require IEnumerable<T>, on the other hand, then they can pass in any collection.

The best place to fnd information on the class heiarchy in .NET is MSDN.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜