Free mag vol1 | Page 394

CHAPTER 9  COLLECTIONS AND GENERICS A First Look at Generic Collections When you use generic collection classes, you rectify all of the previous issues, including boxing/unboxing penalties and a lack of type safety. Also, the need to build a custom (generic) collection class becomes quite rare. Rather than having to build unique classes that can contain people, cars, and integers, you can use a generic collection class and specify the type of type. Consider the following method, which uses the generic List class (in the System.Collections.Generic namespace) to contain various types of data in a strongly typed manner (don’t fret the details of generic syntax at this time): static void UseGenericList() { Console.WriteLine("***** Fun with Generics *****\n"); // This List<> can hold only Person objects. List morePeople = new List(); morePeople.Add(new Person ("Frank", "Black", 50)); Console.WriteLine(morePeople[0]); // This List<> can hold only integers. List moreInts = new List(); moreInts.Add(10); moreInts.Add(2); int sum = moreInts[0] + moreInts[1]; } // Compile-time error! Can't add Person object // to a list of ints! // moreInts.Add(new Person()); The first List object can contain only Person objects. Therefore, you do not need to perform a cast when plucking the items from the container, which makes this approach more type safe. The second List can contain only integers, all of which are allocated on the stack; in other words, there is no hidden boxing or unboxing as you found with the nongeneric ArrayList. Here is a short list of the benefits generic containers provide over their nongeneric counterparts. • Generics provide better performance because they do not result in boxing or unboxing penalties when storing value types. • Generics are type safe because they can contain only the type of type you specify. • Generics greatly reduce the need to build custom collection types because you specify the “type of type” when creating the generic container.  Source Code You can find the IssuesWithNonGenericCollections project under the Chapter 9 subdirectory. 333