Return ReadOnlyCollection from a method with a return type of IList

Here I have the following bit of code:

private IList<IState> _states = new List<IState>(); private ReadOnlyCollection<IState> _statesViewer; public IList<IState> States { get { return _statesViewer; } } 

I find it usually preferable to return the interfaces rather than the concrete classes themselves, but in this case I should not set the States a ReadOnlyCollection property as the return type?

Any user of my library will think that you can do something that you can do with IList , if I install it like this, which means adding elements. This is not true, and I definitely break the contract by revealing it as an IList.

Am I right from this point of view, or is something else missing?

+4
source share
4 answers

Do everything that makes the API clear. If the caller only needs to list it, you can expose it as an IEnumerable<T> , but I will not worry about exposing it as ReadOnlyCollection . You can declare a user type (interface or class) with only an index and an enumerator, of course

+6
source

If it were me, I would just expose it as

 IEnumerable<IState> 
+3
source

IEnumerable<T> is a good choice for any public property that represents a sequence.

This is the smallest possible contract, which is still the sequence that helps you stay unbound.

It provides a rich set of operations in Linq for facilities, so you offer your consumer more power.

+2
source

In some cases, I accept IEnumerable<IState> if people are only allowed to run this list. But if I need more built-in functions for the outside world, such as an index operator, Count, Contains, IndexOf, etc., I will give them ReadOnlyCollection as an IList and write in the documentation that it is read-only.

+2
source

Source: https://habr.com/ru/post/1307987/


All Articles