CHAPTER 9 COLLECTIONS AND GENERICS
The Issue of Type Safety
We touched on the issue of type safety when we looked at unboxing operations. Recall that you must
unbox your data into the same data type it was declared as before boxing. However, there is another
aspect of type safety you must keep in mind in a generic-free world: the fact that a majority of the classes
of System.Collections can typically hold anything whatsoever because their members are prototyped to
operate on System.Objects. For example, this method builds an ArrayList of random bits of unrelated
data:
static void ArrayListOfRandomObjects()
{
// The ArrayList can hold anything at all.
ArrayList allMyObjects = new ArrayList();
allMyObjects.Add(true);
allMyObjects.Add(new OperatingSystem(PlatformID.MacOSX, new Version(10, 0)));
allMyObjects.Add(66);
allMyObjects.Add(3.14);
}
In some cases, you will require an extremely flexible container that can hold literally anything (as
seen here). However, most of the time you desire a type-safe container that can operate only on a
particular type of data point. For example, you might need a container that can hold only database
connections, bitmaps, or IPointy-compatible objects.
Prior to generics, the only way you could address this issue of type safety was to create a custom
(strongly typed) collection class manually. Assume you wish to create a custom collection that can
contain only objects of type Person:
public class Person
{
public int Age {get; set;}
public string FirstName {get; set;}
public string LastName {get; set;}
public Person(){}
public Person(string firstName, string lastName, int age)
{
Age = age;
FirstName = firstName;
LastName = lastName;
}
}
public override string ToString()
{
return string.Format("Name: {0} {1}, Age: {2}",
FirstName, LastName, Age);
}
To build a collection which can hold only Person objects, you could define a
System.Collections.ArrayList member variable within a class named PersonCollection and configure
all members to operate on strongly typed Person objects, rather than on System.Object types. Here is a
simple example (a production-level custom collection could support many additional members and
330