#534 – What Good Are Generics?

generic class takes one or more type parameters, serving as a sort of template for an actual class.

Assume you want to implement a Stack type and that we want to create several kinds of stacks–e.g. a stack of Movie objects, a stack of integers, etc.

Without generics, we could create a new class for each data item, e.g. MovieStackIntStack.  But this would result in a lot of duplicated code.

We could create a stack of object instances, since everything inherits from object.  But this would allow mixing and matching objects of different types in the stack.  It could also lead to lower performance, as value types were boxed/unboxed when added/removed from the stack.

The compromise is to use generics, e.g. Stack<Movie> and Stack<int>.  Then at run-time, we really have two separate types (constructed types), each of which is strongly typed.  But we’ve shared all of the code.

Advertisements