Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List<T> readonly with a private set

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;}
like image 510
Jon Avatar asked Jan 20 '11 15:01

Jon


5 Answers

I think you are mixing concepts.

public List<string> myList {get; private set;}

is already "read-only". That is, outside this class, nothing can set myList to a different instance of List<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:

private List<string> actualList = new List<string>();
public ReadOnlyCollection<string> myList
{
  get{ return actualList.AsReadOnly();}
}

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 can not modify.

like image 58
Philip Rieck Avatar answered Oct 22 '22 06:10

Philip Rieck


If you want readonly collection use ReadOnlyCollection<T>, not List<T>:

public ReadOnlyCollection<string> MyList { get; private set; }
like image 40
Darin Dimitrov Avatar answered Oct 22 '22 07:10

Darin Dimitrov


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; }
}
like image 11
Sergey Berezovskiy Avatar answered Oct 22 '22 08:10

Sergey Berezovskiy


There's a collection called ReadOnlyCollection<T> - is that what you're looking for?

like image 4
Joe Enos Avatar answered Oct 22 '22 08:10

Joe Enos


Return a ReadOnlyCollection, which implements IList<>

private List<string> myList;

public IList<string> MyList
{
  get{return myList.AsReadOnly();}
}
like image 10
Sean Avatar answered Oct 22 '22 06:10

Sean