4.8. 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 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);}
}
}Lottery has a List<int> of winning numbers that it fills in the constructor. The interesting part is that it also exposes a property called Results, which returns a ReadOnlyCollectiontyped 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 ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access