Using Generic Collections


So far you have seen the basics of how you can implement generics in your own code as you develop solutions in C# 2.0. One of the most common uses of generics is in the implementation and manipulation of strongly typed collections. This section of the chapter gives you samples of how to work with some of the most common generic collection types available in version 2.0 of the .NET Framework: the Dictionary<> class, the List<> class, the Queue<> class, and the Stack<> class.

Using the Dictionary Class

The Dictionary class is designed to store values keyed to a lookup value. Traditionally programmers have used this class to store values associated with strings such as names, keywords, or GUIDs, but you can use an object of any type as the key and an object of any type as the value.

Adding generics to the picture allows you to avoid the use of costly System.Object instances as both the key and value, and you can specify the type of the key and the type of the value at the time of instantiation using type parameters, as shown in the following sample snippet:

// Test a Dictionary Dictionary<string, int> monthDays = new Dictionary<string, int>(); monthDays["January"] = 31; monthDays["February"] = 28; monthDays["March"] = 31; Console.WriteLine("March has " + monthDays["March"].ToString() + " days."); 


The preceding sample creates and manipulates a Dictionary<> class where all of the keys are strings, and all of the values are numbers, storing the number of days in each month.

Using the List Class

The List<> class is fairly self-explanatory. Its sole purpose is the storage of a list of items. Without generics, Lists were responsible for storing a list of System.Object types, and whenever the developer needed a true data type out of the list, it would involve type-casting operations and potentially convoluted code. As you can see in the following example, creating and using arbitrary lists of strongly typed data has never been easier:

// Using the List class List<Customer> custList = new List<Customer>(); Customer newCust = new Customer(); newCust.LastName = "Hoffman"; newCust.FirstName = "Kevin"; newCust.CustomerID = 1; custList.Add(newCust); Console.WriteLine(     string.Format("There are {0} customers, the first one is {1} {2}",     custList.Count, custList[0].FirstName, custList[0].LastName)); 


The preceding code produces the following output:

There are 1 customers, the first one is Kevin Hoffman 


Something to pay attention to is the fact that you can now write code like the following without having to write any of your own custom classes:

custList[0].FirstName 


To get a list to work as shown in the preceding line of code, developers used to have to spend countless hours creating their own strongly typed collection classes. Now you can create strongly typed collections at runtime with no performance loss and no typecasting required in a way that makes your code easier to read and reuse.

Using the Queue Class

As you saw in Chapter 4, "Arrays and Collections," the Queue class is designed as a FIFO (First-In First-Out) collection. When you enqueue an item, it remains at the front of the Queue. As you add more items to the Queue, they stack up at the end the same as people would while waiting in line to get into a movie or to reach that elusive bank teller. Each time you dequeue an item from the Queue, you remove an item from the beginning of the collection and can then process it. The generic Queue<> class allows you to specify the data type of the items in the queue at the time of instantiation, as shown in the following sample:

Queue<Customer> custQ = new Queue<Customer>(); custQ.Enqueue(newCust); Customer dqCust = custQ.Dequeue(); Console.WriteLine(     string.Format("Dequeued  the following customer: {0} {1}",     dqCust.FirstName,  dqCust.LastName)); 


Using the Stack Class

In contrast to the Queue<> class, the Stack<> class is a LIFO (Last-in First-out) collection. If you think of a pile of items sitting on the floor representing a stack, you know that in order to get to the item on the bottom of the stack, you have to remove all of the items on top first. The same goes for the Stack<> class; when you push an item onto a stack, it goes on top, and when you pop an item off the stack, you take the topmost item. You can also peek at the item currently sitting on top of the stack without removing it. The following code illustrates pushing items onto a generic stack and popping them off. To be sure you know how stacks work, you can play with the order in which items are pushed to see the results:

Stack<Customer> custStack = new Stack<Customer>(); Customer cust1 = new Customer(); cust1.FirstName = "John"; cust1.LastName = "Doe"; cust1.CustomerID = 99; custStack.Push(newCust); custStack.Push(cust1); Customer popCust = custStack.Pop(); Console.WriteLine(     string.Format("Customer popped off the stack was {0} {1}",     popCust.FirstName, popCust. LastName)); 




Microsoft Visual C# 2005 Unleashed
Microsoft Visual C# 2005 Unleashed
ISBN: 0672327767
EAN: 2147483647
Year: 2004
Pages: 298

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net