How can I expose a List
so that it is readonly, but can be set privately?
This doesn\'t work:
public List myList
If you want readonly collection use ReadOnlyCollection<T>, not List<T>
:
public ReadOnlyCollection<string> MyList { get; private set; }
private List<string> _items = new List<string>();
public ReadOnlyCollection<string> Items
{
get { return _items.AsReadOnly(); }
private set { _items = value }
}
In the .NET 4.5 framework you can expose only the IReadOnlyList interface. Something like:
private List<string> _mylist;
public IReadOnlyList<string> myList { get {return _myList;} }
or if you want to prevent unwanted casting to IList
private List<string> _mylist;
public IReadOnlyList<string> myList { get {return new List<string>(_myList);} }
I prefer to use IEnumerable
private readonly List<string> _list = new List<string>();
public IEnumerable<string> Values // Adding is not allowed - only iteration
{
get { return _list; }
}
Return a ReadOnlyCollection, which implements IList<>
private List<string> myList;
public IList<string> MyList
{
get{return myList.AsReadOnly();}
}
There's a collection called ReadOnlyCollection<T>
- is that what you're looking for?