How can I expose a List
so that it is readonly, but can be set privately?
This doesn\'t work:
public List myList
You can use List's AsReadOnly() method to return a read-only wrapper.
You could also create your normal list, but expose it through a property of type IEnumerable
private List<int> _list = new List<int>();
public IEnumerable<int> publicCollection{
get { return _list; }
}
Here is one way
public class MyClass
{
private List<string> _myList;
public ReadOnlyCollection<string> PublicReadOnlyList { get { return _myList.AsReadOnly(); } }
public MyClass()
{
_myList = new List<string>();
_myList.Add("tesT");
_myList.Add("tesT1");
_myList.Add("tesT2");
//(_myList.AsReadOnly() as List<string>).Add("test 5");
}
}