2

I realize that since .NET 4.5 that the ReadOnlyCollection<T> class implements the new interface IReadOnlyCollection<T> but I am constrained to an older version of the library which doesn't have this.

I would like to know which of the better is considered to be best practice:

public sealed class OptionA {

    /// <summary>
    /// Gets a read-only list of numbers.
    /// </summary>
    public ReadOnlyCollection<int> SomeNumbers {
        get { return new ReadOnlyCollection<int>(_someNumbers); }
    }

    ...

}

public sealed class OptionB {

    /// <summary>
    /// Gets a read-only list of numbers.
    /// </summary>
    public IList<int> SomeNumbers {
        get { return new ReadOnlyCollection<int>(_someNumbers); }
    }

    ...

}
Lea Hayes
  • 62,536
  • 16
  • 62
  • 111
  • Best practice under what circumstances? It depends on which one you want. – Ant P Oct 28 '14 at 18:44
  • There isn't much point in suggesting to the client programmer that the Add() method is going to work. – Hans Passant Oct 28 '14 at 18:46
  • @BartoszKP Since `IList` provides random access and `IEnumerable` does not. – Lea Hayes Oct 28 '14 at 20:12
  • @HansPassant I agree, that is certainly a nice trait that the mutable methods are hidden. – Lea Hayes Oct 28 '14 at 20:15
  • @AntP Where possible I like to expose interfaces rather than a concrete implementation. In the case of this wrapper class I was unsure as to how people typically expose the read-only collections with it in their libraries. – Lea Hayes Oct 28 '14 at 20:16
  • @BartoszKP Thanks! I wasn't aware of that implementation detail in Linq. That is great to know. Post this as the answer and I will accept :) – Lea Hayes Oct 28 '14 at 20:28

1 Answers1

3

You can also use IEnumerable<T> - it will make your code as loosely coupled as possible in this case. It also provides random access with the ElementAt<T> method, which will work with O(1) complexity if the actual type implements IList<T>:

If the type of source implements IList<T>, that implementation is used to obtain the element at the specified index. Otherwise, this method obtains the specified element.

Exposing IList<T> or ReadOnlyCollection<T> could be useful if you really wanted to stress the fact that random access with constant-time complexity is available. Deciding which one really depends on a particular scenario.

BartoszKP
  • 34,786
  • 15
  • 102
  • 130