.NET Zone is brought to you in partnership with:

.NET developer/architect. Been coding since 1996. Jonas is a DZone MVB and is not an employee of DZone and has posted 18 posts at DZone. You can read more from them at their website. View Full User Profile

Alternative to IEnumerable for Read-Only Collections

09.28.2013
| 2628 views |
  • submit to reddit

.NET 4.5 introduced a new interface which is great if you want to expose a collection as readonly.

The problem with IEnumerable<T> is that it’s forward only. i.e. there is no guarantee that you can traverse it multiple times. The collection size might also be unknown, depending on the implementation.

So if you want to expose a collection which can be traversed multiple times and where the size is know there is as of .NET 4.5 another alternative. And that’s IReadOnlyList<T>. It inherits another new interface calledIReadOnlyCollection<out T>.

Code

public interface IReadOnlyCollection<out T> 
      : IEnumerable<T>, 
        IEnumerable
{
    int Count { get; }
}
public interface IReadOnlyList<out T> 
      : IReadOnlyCollection<T>
      , IEnumerable<T>
      , IEnumerable
{
    T this[int index] { get; }
}

Usage example

public class MyRepository
{
    public IReadOnlyList<User> FindUsers(string lastName)
    {
        // [...]
    }

    // [...]
}
Published at DZone with permission of Jonas Gauffin, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)