Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# return non-modifiable list

I have a class which contains a List<Item> I have a getter on the class that returns this. Is there some thing I can do to ensure the user who calls cannot modify the returned List? (Since it's a reference type - I believe changes to the returned reference would affect the list stored in the source object)

like image 668
Aishwar Avatar asked Dec 12 '22 19:12

Aishwar


1 Answers

Return your List wrapped in ReadOnlyCollection<T>.

  public ReadOnlyCollection<Item> MyROList {
    get { return new ReadOnlyCollection<Item>(myList); }
  }

  private List<Item> myList = new List<Item>();

More details elsewhere on SO.

Depending on usage of your class, you could allocate the ReadOnlyCollection at construction time and link it to the underlying List. If you expect to always or most of the time need this property, and the underlying List is in place at that time, then this is sensible. Otherwise you could leave the ReadOnlyCollection<Item> class member null and allocate it on demand in the getter if it is null (taking thread safety into account).

like image 110
Steve Townsend Avatar answered Dec 15 '22 09:12

Steve Townsend