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.

Jaganathan BantheswaranPosted Apr 14, 2013, 1:00 PM
Nice article Zoran....
Zoran HorvatPosted Apr 14, 2013, 8:42 AM
Jaganathan, I've been solving the same problem and found it relatively simple to control collection changes using ObservableCollection<T> collection type. Just to demonstrate the power of ObservableCollection, I've added requirement that only unique elements can be added to the collection property. You can read the whole solution in this article: http://www.sysexpand.com/?path=howto/collection-property