Search code examples
.netmonoreadonly-collection

Expose IList<T> or ReadOnlyCollection<T> for Read-Only Property?


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); }
    }

    ...

}

Solution

  • 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.