
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Making Read-Only Collections the Generic Way
|
269
using a foreach loop, with KeyValuePair being the type returned. While accessing ele-
ments of the
ReversibleSortedList<T>, they may only be read from. The usual itera-
tor syntax prohibits updating or deleting elements of the list while reading, as it will
invalidate the iterator.
See Also
See Recipe 6.3; see the “SortedList,” “Generic KeyValuePair Structure,” and
“Generic SortedList” topics in the MSDN documentation.
4.9 Making Read-Only Collections the Generic Way
Problem
You have a collection of information that you want to expose from your class, but
you don’t want any users modifying the collection.
Solution
Use the ReadOnlyCollection<T> wrapper to easily support collection classes that can-
not be modified. For example, a
Lottery class that contained the winning lottery
numbers should make the winning numbers accessible, but not allow them to be
changed:
public class Lottery
{
// Make a list.
List<int> _numbers = null;
public Lottery( )
{
// Make the internal list
_numbers = new List<int>(5);
// Add values
_numbers.Add(17);
_numbers.Add(21);
_numbers.Add(32);
_numbers.Add(44);
_numbers.Add(58);
}
public ReadOnlyCollection<int> Results
{
// Return a wrapped copy of the results.
get { return new ReadOnlyCollection<int>(_numbers); }
} ...