Free mag vol1 | Page 402

CHAPTER 9  COLLECTIONS AND GENERICS BottomRight = new Point { X = 100, Y = 100}}, new Rectangle {TopLeft = new Point { X = 5, Y = 5 }, BottomRight = new Point { X = 90, Y = 75}} }; foreach (var r in myListOfRects) { Console.WriteLine(r); } Working with the List Class Create a brand new Console Application project named FunWithGenericCollections. Note that your initial C# code file already imports the System.Collections.Generic namespace. The first generic class you will examine is List, which you’ve already seen once or twice in this chapter. The List class is bound to be your most frequently used type in the System.Collections.Generic namespace because it allows you to resize the contents of the container dynamically. To illustrate the basics of this type, ponder the following method in your Program class, which leverages List to manipulate the set of Person objects seen earlier in this chapter; you might recall that these Person objects defined three properties (Age, FirstName, and LastName) and a custom ToString() implementation: static void UseGenericList() { // Make a List of Person objects, filled with // collection/object init syntax. List people = new List() { new Person {FirstName= "Homer", LastName="Simpson", Age=47}, new Person {FirstName= "Marge", LastName="Simpson", Age=45}, new Person {FirstName= "Lisa", LastName="Simpson", Age=9}, new Person {FirstName= "Bart", LastName="Simpson", Age=8} }; // Print out # of items in List. Console.WriteLine("Items in list: {0}", people.Count); // Enumerate over list. foreach (Person p in people) Console.WriteLine(p); // Insert a new person. Console.WriteLine("\n->Inserting new person."); people.Insert(2, new Person { FirstName = "Maggie", LastName = "Simpson", Age = 2 }); Console.WriteLine("Items in list: {0}", people.Count); // Copy data into a new array. Person[] arrayOfPeople = people.ToArray(); for (int i = 0; i < arrayOfPeople.Length; i++) { Console.WriteLine("First Names: {0}", arrayOfPeople[i].FirstName); } 341