Click here to Skip to main content
13,349,539 members (50,522 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


3 bookmarked
Posted 30 May 2011

Returning read-only collection

, 4 Jun 2011
Rate this:
Please Sign up or sign in to vote.
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
            return m_privateCollection.AsReadOnly();

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.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Nick Alexeev
Systems Engineer Prolitech
United States United States
doing business as Prolitech
Redwood City, CA

blog (mostly technical)

You may also be interested in...


Comments and Discussions

-- There are no messages in this forum --
Permalink | Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.180111.1 | Last Updated 5 Jun 2011
Article Copyright 2011 by Nick Alexeev
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid