#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

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: