Read-Only List in C#

You can expose a List<T> as a ReadOnlyCollection<T> by using the method AsReadOnly()

C# 5.0 and earlier

class Foo {

  private List<int> myList;

  public ReadOnlyCollection<int> ReadOnlyList {
     get {
         return myList.AsReadOnly();
     }
  }
}

C# 6.0 and later (using Expression Bodied Properties)

class Foo { 

  private List<int> myList;

  public ReadOnlyCollection<int> ReadOnlyList => myList.AsReadOnly();

}

The neat thing is that if you add/remove anything from your private list its also reflected in the returned ReadOnlyCollection


If you want a read-only view of a list you could use ReadOnlyCollection<T>.

class Foo {
    private ReadOnlyCollection<int> myList;
}

i would go for

public sealed class Foo
{
    private readonly List<object> _items = new List<object>();

    public IEnumerable<object> Items
    {
        get
        {
            foreach (var item in this._items)
            {
                yield return item;
            }
        }
    }
}

Tags:

C#

.Net

List