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)
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With