.NET Tip of The Day
Learn one new .NET trick every day
Быстрое пополнение счета телефона      Login or Join

Return read-only collection if you want to control its modification

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.

9/26/2007
RSS .NET Tip of The Day
Subscribe to receive one tip from the .NET Tips and Tricks Community per day.
Previous Tips of The Day
The best of the .NET Tips & Tricks Community.
.NET Practitioners .NET Tips & Tricks Community
Every .NET practitioner has a trick up in their sleeve. This is the place to share it with other .NET people.
Submit a Tip
Discovered a new trick? Share it with others.
My Tips
Manage tips you authored.