How can I expose a List<T> so that it is readonly, but can be set privately?
This doesn’t work:
public List<string> myList {readonly get; private set; }
Even if you do:
public List<string> myList {get; private set; }
You can still do this:
myList.Add("TEST"); //This should not be allowed
I guess you could have:
public List<string> myList {get{ return otherList;}}
private List<string> otherList {get;set;}
I think you are mixing concepts.
is already "read-only". That is, outside this class, nothing can set
myListto a different instance ofList<string>However, if you want a readonly list as in "I don’t want people to be able to modify the list contents", then you need to expose a
ReadOnlyCollection<string>. You can do this via:Note that in the first code snippet, others can manipulate the List, but can not change what list you have. In the second snippet, others will get a read-only list that they cannot modify.