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 { ret
You can expose it AsReadOnly. That is, return a read-only IList wrapper. For example ...
public ReadOnlyCollection List
{
get { return _lst.AsReadOnly(); }
}
Just returning an IEnumerable is not sufficient. For example ...
void Main()
{
var el = new ExposeList();
var lst = el.ListEnumerator;
var oops = (IList)lst;
oops.Add( 4 ); // mutates list
var rol = el.ReadOnly;
var oops2 = (IList)rol;
oops2.Add( 5 ); // raises exception
}
class ExposeList
{
private List _lst = new List() { 1, 2, 3 };
public IEnumerable ListEnumerator
{
get { return _lst; }
}
public ReadOnlyCollection ReadOnly
{
get { return _lst.AsReadOnly(); }
}
}
Steve's answer also has a clever way to avoid the cast.