65.9K
CodeProject is changing. Read more.
Home

Returning read-only collection

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.50/5 (2 votes)

May 31, 2011

CPOL
viewsIcon

17465

Returning read-only collection

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 ReadOnlyCollection, which can't be cast into the editable collection.
using System.Collections.ObjectModel;

public class MyClass
{
    private List<MyItem> m_privateCollection = new List<MyItem>();  // private collection
    public ReadOnlyCollection<MyItem> MyItems
    {
        get
        {
            return m_privateCollection.AsReadOnly();
        }
    }
}
Caveats Calling code can modify the contents within collection items:
ReadOnlyCollection<MyItem> myReadOnlyCollection = obj.MyItems;
myReadOnlyCollection[0].Voltage = 1.1f;

The underlying collection can be modified by another thread.

Still, by using ReadOnlyCollection, some bugs can be repelled.