Benefits of Generics
Generics allow
programmers to author, test, and deploy code once, and then reuse that code for
a variety of different data types. While this is true of the first Stack
example as well, the second Stack example allows your program to reuse code
with a negligible performance impact to its applications. For value types, the
first Stack example imposes a significant performance penalty, whereas the
second Stack example eliminates the penalty entirely because you have
eliminated boxing and downcast.
In addition, generics
are checked at compile-time. When your program instantiates a generic class
with a supplied type parameter, the type parameter can only be of the type your
program specified in the class definition. For example, when your program
created a Stack of Customer objects, it was no longer able to push an integer
onto the stack. By enforcing such behavior, you can build code that is more
reliable.
Furthermore, the C#
implementation of generics reduces code bloat when compared to other
strongly-typed implementations. By creating typed collections with generics,
you can avoid the need to create specific versions of each class while
retaining the performance benefits of doing so. For example, your program can
create one parameterized Stack class and avoid having to create an IntegerStack
to store integers, a StringStack to store strings, or a CustomerStack to store
Customer types.
This, of course, leads
to code that is more readable. By creating one Stack class, your program can
encapsulate all behavior associated with a stack in one convenient class. Then,
when you create a Stack of Customer types, it is still obvious that your
program is using a stack data structure, albeit with Customer types stored
within it.
No comments:
Post a Comment