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 believe that generally it is preferable to return interfaces rather than the concrete classes themselves, but in this case, shouldn't I set as the return type of the States
property a ReadOnlyCollection
?
Any user of my library will think it is possible to anything you can do with an IList
if I set it as so, and that means adding elements. That is not true and I'm definitely breaking the contract exposing it as an IList.
Am I right with this view or there is something else I am missing here?
Do whatever makes the API clearest. If the caller only needs to enumerate it you could expose as IEnumerable<T>
, but I wouldn't be concerned about exposing it as ReadOnlyCollection
. You could declare a custom type (interface or class) with just an indexer and enumerator, of course
If it was me, I would simply expose it as
IEnumerable<IState>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With