How should I use properties when dealing with read-only List<T> members

c#, collections, readonly

Solution

You can expose it AsReadOnly. That is, return a read-only `IList<T>` wrapper. For example ...

public ReadOnlyCollection<int> List
{
    get { return _lst.AsReadOnly(); }
}

Just returning an `IEnumerable<T>` is not sufficient. For example ...

void Main()
{
    var el = new ExposeList();
    var lst = el.ListEnumerator;
    var oops = (IList<int>)lst;
    oops.Add( 4 );  // mutates list

    var rol = el.ReadOnly;
    var oops2 = (IList<int>)rol;

    oops2.Add( 5 );  // raises exception
}

class ExposeList
{
  private List<int> _lst = new List<int>() { 1, 2, 3 };

  public IEnumerable<int> ListEnumerator
  {
     get { return _lst; }
  }

  public ReadOnlyCollection<int> ReadOnly
  {
     get { return _lst.AsReadOnly(); }
  }
}

Steve's answer also has a clever way to avoid the cast.

Problem

When I want to make a value type read-only outside of my class I do this: ``` public class myClassInt { private int m_i; public int i { get { return m_i; } } public myClassInt(int i) { m_i = i; } } ``` What can I do to make a `List<T>` type readonly (so they can't add/remove elements to/from it) outside of my class? Now I just declare it public: ``` public class myClassList { public List<int> li; public myClassList() { li = new List<int>(); li.Add(1); li.Add(2); li.Add(3); } } ```

Original source

Related problems