CHAPTER 9 COLLECTIONS AND GENERICS
Console.WriteLine("Array Entry: {0}", s);
}
Console.WriteLine();
// Reverse the array and print again.
Array.Reverse(strArray);
foreach (string s in strArray)
{
Console.WriteLine("Array Entry: {0}", s);
}
}
Console.ReadLine();
While basic arrays can be useful to manage small amounts of fixed-size data, there are many other
times where you require a more flexible data structure, such as a dynamically growing and shrinking
container, or a container that can hold objects that meet only a specific criteria (e.g., only objects
deriving from a specific base class or only objects implementing a particular interface). When you make
use of a simple array, always remember they are “fixed size.” If you make an array of three items, you
only get three items; therefore, the following code would result in a runtime exception (an
IndexOutOfRangeException, to be exact):
static void Main(string[] args)
{
// Make an array of string data.
string[] strArray = { "First", "Second", "Third" };
// Try to add a new item at the end?? Runtime error!
strArray[3] = "new item?";
...
}
To help overcome the limitations of a simple array, the .NET base class libraries ship with a number
of namespaces containing collection classes. Unlike a simple C# array, collection classes are built to
dynamically resize themselves on the fly as you insert or remove items. Moreover, many of the collection
classes offer increased type safety and are highly optimized to process the contained data in a memoryefficient manner. As you read over this chapter, you will quickly notice that a collection class can belong
to one of two broad categories:
•
Nongeneric collections (primarily found in the System.Collections namespace)
•
Generic collections (primarily found in the System.Collections.Generic
namespace)
Nongeneric collections are typically designed to operate on System.Object types and are, therefore,
very loosely typed containers (however, some nongeneric collections do operate only on a specific type
of data, such as string objects). In contrast, generic collections are much more type safe, given that you
must specify the “type of type” they contain upon creation. As you will see, the telltail sign of any generic
item is the “type parameter” marked with angled brackets (for example, List). We will examine the
details of generics (including the many benefits they provide) a bit later in this chapter. For now, let’s
examine some of the key nongeneric collection types in the System.Collections and
System.Collections.Specialized namespaces.
322