ReadOnly collections prevents the modification of the collection which is defined with type ReadOnly.
Let's review the following example:
public class Order
{
private List<OrderItem> _orderItems = new List<OrderItem>();
public ReadOnlyCollection<OrderItem> OrderItems
{
get { return _orderItems.AsReadOnly(); }
}
public void AddOrderItem(OrderItem orderItem)
{
...
_orderItems.Add(orderItem);
}
}
The class has a public property of a collection type and I want to
have "controlled access" to this collection. What I mean is, that a
consumer of these classes should not be able to add an OrderItem
to the collection directly, since some additional action(s) need to be executed. He should always use the AddOrderItem
method if he wants to add an OrderItem
to the Order
.
In such cases keep the collection private, create the necessary
methods to provide the necessary controlled access to the collection and
create a public property which returns a read-only instance of the
collection (by using List<T>.AsReadOnly
method), so that you can iterate through the collection, change
existing instances of objects within the collection, get the number of
objects that are in the collection, etc.