Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a ReadOnlyCollection from a method with an IList return type

Tags:

c#

.net

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?

like image 669
devoured elysium Avatar asked Dec 13 '22 22:12

devoured elysium


2 Answers

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

like image 190
Marc Gravell Avatar answered Dec 15 '22 12:12

Marc Gravell


If it was me, I would simply expose it as

IEnumerable<IState>
like image 37
leppie Avatar answered Dec 15 '22 14:12

leppie