10.4. Identifying Generic Opportunities

This first set of guidelines is focused on describing a specific set of scenarios where you should consider leveraging generics. These items represent areas where you would want to consider refactoring existing code or they may just be patterns you'll want to consider when you're introducing new code. Some of these may be somewhat obvious based on other topics covered elsewhere in this book. However, the goal is to assemble all of these items in one place as a list that you can easily consult as you're working with generics.

10.4.1. Item 1: Use Generic Collections

Data collections are typically one of the most heavily used data types. You likely already have ArrayLists and HashTables strewn throughout your existing code. You were also likely—before generics—to make heavy use of these System.Collections data structures in new code you would be writing. However, with generics, there's really no good reason to continue to use the collections from this namespace.

If there is one area where generics add unquestionable value, it is in the area of collections. Without generics, producers and consumers of non-generic collections were forced to represent contained types as objects. This, of course, meant your code was littered with casts and general type coercion to covert each object to its actual type. It also meant that value types need to be boxed to be represented as object types. Even in cases where you may have tried to limit the impact of ...

Get Professional .NET 2.0 Generics now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.