Collections

for RuBoard

The .NET Framework class library provides an extensive set of classes for working with collections of objects. These classes are all in the System.Collections namespace and implement a number of different kinds of collections, including lists, queues, stacks, arrays, and hashtables. The collections contain object instances. Since all types derive ultimately from object , any built-in or user -defined type may be stored in a collection.

In this section we will look at a representative class in this namespace, ArrayList , and see how to use array lists in our programs.

ArrayList Example

To get our bearings, let's begin with a simple example of using the ArrayList class. An array list, as the name suggests, is a list of items stored like an array. An array list can be dynamically sized and will grow as necessary to accommodate new elements being added.

Collection classes are made up of instances of type object . We will create and manipulate a collection of Customer objects. We could just as easily create a collection of any other built-in or user-defined type. If our type were a value type, such as int , the instance would be boxed before being stored in the collection. When the object is extracted from the collection, it will be unboxed back to int .

Our example program is CustomerCollection . It initializes a list of customers and then lets the user show the customers, register a new customer, unregister a customer, and change an email address. A simple "help" method displays the commands that are available:

 Enter command, quit to exit  H> help  The following commands are available:          register   register a customer          unregister unregister a customer          email      change email address          show       show customers          quit       exit the program 

Before examining the code it would be a good idea to run the program to register a new customer, show the customers, change an email address, unregister a customer, and show the customers again. Here is a sample run of the program:

 H> show  id (-1 for all): -1     1   Rocket       Squirrel    rocky@frosbitefalls.com     2   Bullwinkle   Moose       moose@wossamotta.edu  H> register  first name: Bob  last name: Oberg  email address: oberg@objectinnovations.com  id = 3  H> email  customer id: 1  email address: rocky@objectinnovations.com  H> unregister  id: 2  H> show  id (-1 for all): -1     1   Rocket       Squirrel  rocky@objectinnovations.com     3   Bob          Oberg  oberg@objectinnovations.com 
Customers Class

All the code for this project is in the folder CustomerCollection . The file customer.cs has code for the Customer and Customers classes. The code for Customer is almost identical to what we looked at previously. The only addition is a special constructor that instantiates a Customer object with a specified id. We use this constructor in the Customers class when we remove an element and when we check if an element is present in the collection.

 public class Customer  {  ...  public Customer(int id)   {   CustomerId = id;   FirstName = "";   LastName = "";   EmailAddress = "";   }  ...  } 

The Customers class contains a list of customers, represented by an ArrayList .

 public class Customers  {  private ArrayList customers;  public Customers()     {        customers = new ArrayList();        RegisterCustomer("Rocket", "Squirrel",                         "rocky@frosbitefalls.com");        RegisterCustomer("Bullwinkle", "Moose",                         "moose@wossamotta.edu");     }     public int RegisterCustomer(string firstName,        string lastName, string emailAddress)     {        Customer cust = new Customer(firstName, lastName,                                     emailAddress);  customers.Add(cust);  return cust.CustomerId;     }     public void UnregisterCustomer(int id)     {        Customer cust = new Customer(id);  customers.Remove(cust);  }     public void ChangeEmailAddress(int id,                                    string emailAddress)     {  foreach (Customer cust in customers)  {           if (cust.CustomerId == id)           {              cust.EmailAddress = emailAddress;              return;           }        }        throw new Exception("id " + id + " not found");     }     public void ShowCustomers(int id)     {        if (!CheckId(id) && id != -1)           return;  foreach (Customer cust in customers)  {           if (id == -1  id == cust.CustomerId)           {              string sid =                 cust.CustomerId.ToString().PadLeft(4);              string first = cust.FirstName.PadRight(12);              string last = cust.LastName.PadRight(12);              string email = cust.EmailAddress.PadRight(20);              string str = sid + "   " + first + "   " +                 last + "   " + email;              Console.WriteLine(str);           }        }     }     private bool CheckId(int id)     {        Customer cust = new Customer(id);  return customers.Contains(cust);  }  } 

The lines in the listing in bold show the places where we are using collection class features. In Chapter 3 we have already used foreach with arrays. The reason foreach can be used with arrays is that the Array class, like ArrayList , implements the IEnumerable interface that supports foreach syntax. We will discuss IEnumerable and the other collection interfaces later in this chapter.

The Add and Remove methods , as their names suggest, are used for adding and removing elements from a collection. The Remove method searches for an object in the collection that Equals the object passed as a parameter. Our special constructor creates an object having the id of the element we want to remove. Since we provided an override of the Equals method that bases equality on CustomerId , the proper element will be removed.

Similarly, the Contains method used in our CheckId helper method also relies on the override of the Equals method.

Compare the code in this program with the use of arrays in the code in the previous chapter's case study. The collection code is much simpler. Using collections makes it easy to remove elements as well as add them. Using arrays, you would have to write special code to move array elements to fill in the space where an element was deleted. Also, collections are not declared to have a specific size , but can grow as required.

for RuBoard


Application Development Using C# and .NET
Application Development Using C# and .NET
ISBN: 013093383X
EAN: 2147483647
Year: 2001
Pages: 158

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