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)
I have a class which contains a List<Item> I have a getter on the
Share
Return your List wrapped in
ReadOnlyCollection<T>.More details elsewhere on SO.
Depending on usage of your class, you could allocate the
ReadOnlyCollectionat construction time and link it to the underlyingList. If you expect to always or most of the time need this property, and the underlyingListis in place at that time, then this is sensible. Otherwise you could leave theReadOnlyCollection<Item>class membernulland allocate it on demand in the getter if it isnull(taking thread safety into account).