Generics

Generics

The next chapter is about Generics, which improves upon the performance and other factors related to nongeneric collections. The collections reviewed in this chapter manipulate object types. For this reason, when populating collections with value types, boxing is required. Excessive boxing is both a performance and memory issue. Another problem is type-safeness. You often cast elements that are object types to a specific type. The cast is not type-safe and can cause run-time errors when done incorrectly.

Generics types are classes with type parameters. The type parameter acts as a placeholder for a future type. When a generic type is declared, type arguments are substituted for the type parameters. The type argument is the actual type. At that time, the generic is type-specific, which resolves many of the problems of a nongeneric type. Generic methods, like generic types, have type parameters. However, the type argument can be inferred from the way the method is called.

A complete explanation of generic types and methods follows in Chapter 6.