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
JP's answer regarding returning IEnumerable
is correct (you can down-cast to a list), but here is a technique that prevents the down-cast.
class ExposeList
{
private List _lst = new List() { 1, 2, 3 };
public IEnumerable ListEnumerator
{
get { return _lst.Select(x => x); } // Identity transformation.
}
public ReadOnlyCollection ReadOnly
{
get { return _lst.AsReadOnly(); }
}
}
The identity transformation during enumeration effectively creates a compiler-generated iterator - a new type which is not related to _lst
in any way.