More About Generics - 4.8 Making Read-Only Collections the Generic Way
(Page 4 of 4 )
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 cannot 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()
{
// pick the winning numbers
_numbers = new List<int>(5) { 17, 21, 32, 44, 58 };
}
public ReadOnlyCollection<int> Results
{
// return a wrapped copy of the results
get { return new ReadOnlyCollection<int>(_numbers); }
}
}
Lotteryhas aList<int>of winning numbers that it fills in the constructor. The interesting part is that it also exposes a property calledResults, which returns aReadOnlyCollectiontyped as<int>for seeing the winning numbers. Internally, a newReadOnlyCollection wrapper is created to hold theList<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 = {0, 1, 2 };
ReadOnlyCollection<int> readOnlyItems =
new ReadOnlyCollection<int>(items);
This provides a way to standardize the read-only properties on classes to make it easier for consumers of the class to recognize which properties are read-only simply by the return type.
See Also
The “ReadOnlyCollection” topic in the MSDN documentation.
Please check back next week for the conclusion of this article.
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |
|
This article is excerpted from chapter four of the C# 3.0 Cookbook, Third Edition, written by Jay Hilyard and Stephen Teilhet (O'Reilly, 2008; ISBN: 059651610X). Check it out today at your favorite bookstore. Buy this book now.
|
|