
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
270
|
Chapter 4: Generics
ReadOnlyCollection typed as <int> for seeing the winning numbers. Internally, a new
ReadOnlyCollection wrapper is created to hold the List<int> that has the numbers in
it, and then this instance is returned for use by the user.
If users then attempt to set a value on the collection, they get a compile error:
Lottery tryYourLuck = new Lottery( );
// Print out the results.
for (int i = 0; i < tryYourLuck.Results.Count; i++)
{
Console.WriteLine("Lottery Number " + i + " is " + tryYourLuck.Results[i]);
}
// Change it so we win!
tryYourLuck.Results[0]=29;
//The above line gives // Error 26 // Property or indexer
// 'System.Collections.ObjectModel.ReadOnlyCollection<int>.this[int]'
// cannot be assigned to -- it is read only
Discussion
The main advantage ReadOnlyCollection provides is the flexibility to use it with any
collection that supports
IList or IList<T> as an interface. ReadOnlyCollection can be
used to wrap a regular array like this:
int [] items = new int[3];
items[0]=0;
items[1]=1;
items[2]=2;
new ReadOnlyCollection<int>(items);
This provides a way to standardize the read-only properties on classes to make it eas-
ier for consumers of the class to recognize which properties are read-only simply by
the return type.
See Also
See the “IList” and “Generic IList” topics in ...