CHAPTER 9 COLLECTIONS AND GENERICS
}
Here, you use initialization syntax to populate your List with objects, as a shorthand notation
for calling Add() multiple times. After you print out the number of items in the collection (as well as
enumerate over each item), you invoke Insert(). As you can see, Insert() allows you to plug a new item
into the List at a specified index.
Finally, notice the call to the ToArray() method, which returns an array of Person objects based on
the contents of the original List. From this array, you loop over the items again using the array’s
indexer syntax. If you call this method from within Main(), you get the following output:
***** Fun with Generic Collections *****
Items
Name:
Name:
Name:
Name:
in list: 4
Homer Simpson, Age: 47
Marge Simpson, Age: 45
Lisa Simpson, Age: 9
Bart Simpson, Age: 8
->Inserting new person.
Items in list: 5
First Names: Homer
First Names: Marge
First Names: Maggie
First Names: Lisa
First Names: Bart
The List class defines many additional members of interest, so be sure to consult the .NET
Framework documentation for more information. Next, let’s look at a few more generic collections,
specifically Stack, Queue, and SortedSet. This should get you in a great position to understand
your basic choices regarding how to hold your custom application data.
Working with the Stack Class
The Stack class represents a collection that maintains items using a last-in, first-out manner. As you
might expect, Stack defines members named Push() and Pop() to place items onto or remove items
from the stack. The following method creates a stack of Person objects:
static void UseGenericStack()
{
Stack stackOfPeople = new Stack();
stackOfPeople.Push(new Person
{ FirstName = "Homer", LastName = "Simpson", Age = 47 });
stackOfPeople.Push(new Person
{ FirstName = "Marge", LastName = "Simpson", Age = 45 });
stackOfPeople.Push(new Person
{ FirstName = "Lisa", LastName = "Simpson", Age = 9 });
342