Free mag vol1 | Page 405

CHAPTER 9  COLLECTIONS AND GENERICS Table 9-6. Members of the Queue Type Select Member of Queue Meaning in Life Dequeue() Removes and returns the object at the beginning of the Queue. Enqueue() Adds an object to the end of the Queue. Peek() Returns the object at the beginning of the Queue without removing it. Now let’s put these methods to work. You can begin by leveraging your Person class again and building a Queue object that simulates a line of people waiting to order coffee. First, assume you have the following static helper method: static void GetCoffee(Person p) { Console.WriteLine("{0} got coffee!", p.FirstName); } Now assume you have this additional helper method, which calls GetCoffee() internally: static void UseGenericQueue() { // Make a Q with three people. Queue peopleQ = new Queue(); peopleQ.Enqueue(new Person {FirstName= "Homer", LastName="Simpson", Age=47}); peopleQ.Enqueue(new Person {FirstName= "Marge", LastName="Simpson", Age=45}); peopleQ.Enqueue(new Person {FirstName= "Lisa", LastName="Simpson", Age=9}); // Peek at first person in Q. Console.WriteLine("{0} is first in line!", peopleQ.Peek().FirstName); } 344 // Remove each person from Q. GetCoffee(peopleQ.Dequeue()); GetCoffee(peopleQ.Dequeue()); GetCoffee(peopleQ.Dequeue()); // Try to de-Q again? try { GetCoffee(peopleQ.Dequeue()); } catch(InvalidOperationException e) { Console.WriteLine("Error! {0}", e.Message); }