Sometimes, you want a class to expose a collection of items. At the same time, you don’t want the client code to add or remove items from the collection, because that could – for example – break the integrity of the class. Of the ways to achieve this is returning
, which can't be cast into the editable collection.
public class MyClass
private List<MyItem> m_privateCollection = new List<MyItem>(); public ReadOnlyCollection<MyItem> MyItems
Calling code can modify the contents within
ReadOnlyCollection<MyItem> myReadOnlyCollection = obj.MyItems;
myReadOnlyCollection.Voltage = 1.1f;
The underlying collection can be modified by another thread.
Still, by using
, some bugs can be repelled.