A bigger problem is that a list that can hold anything can hold anything. If you make a list to hold
customer data, it could still hold
ints, strings, and PurchaseOrder objects. Your code would need
to do a lot of work guarding against accidentally putting the wrong kind of item in the list.
A much better approach is to use generic classes. These classes take data types in their declarations
so they know what kind of data they will manipulate. Using this kind of class, you can build a list of
integers, strings, or what have you.
The following code declares and initializes a generic
List class.
List<string> names = new List<string>();
The <string> part of the declaration indicates that the class will work with strings. You can put
strings into the list and take strings out of it. You cannot add an integer to the list, just as you can’t
set a string variable equal to an integer. Visual Studio knows that the list works with strings and
won’t let you use anything else.
Note that IntelliSense knows about generic classes and provides help. If you begin a declaration with
List, IntelliSense displays List<> to let you know that it is a generic class.
Now if you type the opening pointy bracket, IntelliSense displays a list of the class’s type parameters
and even describes them as you type. (The
List class has only one type parameter but some such
as
Dictionary have more.) After you finish the declaration, the class knows what data types it will
manipulate, and it can behave as if it were designed with that data type in mind.
Now, with some understanding of generic classes, you’re ready to look at some generic
collection classes.
Lists
A List is a simple ordered list of items. You can declare and initialize a List as in the following code.
List<string> names = new List<string>();
The List class provides several methods for manipulating the items it contains. The three most
important are
Add, Remove, and RemoveAt.
The
Add method adds a new item to the end of the list, automatically resizing the List if neces-
sary. This is easier than adding an item to an array, which requires you to resize the array first.
The
Remove method removes a particular item from the list. Note that you pass the target item to
Remove, not the index of the item that you want to remove. If you know that the string “Zaphod”
is in the list
names, the following code removes the first instance of that name from the list:
names.Remove(“Zaphod”);
The Remove method removes only the first occurrence of an item from the List.
596906book.indd 201 4/8/10 7:40:04 AM