What does the return type ICollection <Person> mean?

I am looking at some code examples for Entity Framework 4, and the author has created a method that returns ICollection <Person>. I know that ICollection is an interface. I know that Person is the type of object in the collection. I know that I am returning the Faces collection.

Question. Why is ICollection? Why not List <>? Why is the interface used like this? I used interfaces as β€œdrawings” for classes, specifying the required elements, but I really don't understand the usage here.

+4
source share
3 answers

It is often better to return interfaces instead of specific classes in the open API.

This allows a change to be made later. For example, at the moment it may return List<T> . However, later optimization could be done to return another type of collection that might have better memory efficiency, allow streaming, or one of many other benefits. As long as this class still implements ICollection<T> , the implementation can freely switch without causing an API violation.

+12
source

One of the key points of GoF Design Patterns is interface programming, not implementation. The reason for this is his freedom. By returning an interface instead of a specific type, the implementation can be more easily changed in the future without affecting the calling code.

0
source

If your users do not want this, your API should disclose as little implementation details as possible, in which case using List<Person> is implementation detail. For example, if you or your users know that they want to access the result set by index, then it is better to return IList<Person> instead of ICollection<Person> , but if you are not sure about user scenarios, you should identify most basic abstractions, since you can (i.e. in this case maybe IEnumerable<Person> will be enough).

And remember that if recently you decide to use a more derived return type, it will not violate existing clients, but you cannot use a more based return type without interrupting some of them.

0
source

All Articles