What is the real advantage of returning ICollectio

2019-04-04 10:31发布

I've read a couple of blog post mentioning that for public APIs we should always return ICollection (or IEnumerable) instead of List. What is the real advantage of returning ICollection instead of a List?

Thanks!

Duplicate: What is the difference between List (of T) and Collection(of T)?

5条回答
再贱就再见
2楼-- · 2019-04-04 11:20

An enumerator only returns one entity at a time as you iterate over it. This is because it uses a yield return. A collection, on the other hand, returns the entire list, requiring that the list be stored completely in memory.

The short answer is that enumerators are lighter and more efficient.

查看更多
啃猪蹄的小仙女
3楼-- · 2019-04-04 11:26

I would think IList would be more appropriate, but...

查看更多
Lonely孤独者°
5楼-- · 2019-04-04 11:31

It gives you more freedom when choosing the Underlying data structure.

A List assumes that the implementation supports indexing, but ICollection makes no such assumption.

This means that if you discover that a Set might provide better performance since ordering is irrelevant, then you're free to change your approach without affecting clients.

It's basic encapsulation.

查看更多
地球回转人心会变
6楼-- · 2019-04-04 11:31

ICollection is just an interface, while List is a specific implementation of that interface. What if you wanted to later on use some other container besides a list? If you publicly expose an ICollection interface, you can change your internal container to something else later on - as long as the new container also implements the ICollection interface.

查看更多
登录 后发表回答