Information Technology Reference
In-Depth Information
What Are Generics?
With the language constructs you've learned so far, you can build powerful objects of many dif-
ferent types. You do this mostly by declaring classes that encapsulate the behavior you want,
and then creating instances of those classes.
All the types used in the class declarations so far have been specific types—either
programmer-defined, or supplied by the language or the BCL. There are times, however, when
a class would be more useful if you could “distill” or “refactor” out its actions and apply them
not just to the data types for which they are coded, but for other types as well.
Generics allow you to do just that. You can refactor your code and add an additional layer
of abstraction so that, for certain kinds of code, the data types are not hard-coded. This is par-
ticularly designed for cases in which there are multiple sections of code performing the same
instructions, but on different data types.
That might sound pretty abstract, so we'll start with an example that should make things
clearer.
A Stack Example
Suppose first that you have created the following code, which declares a class called
MyIntStack , which implements a stack of int s. It allows you to push int s onto the stack
and pop them off.
class MyIntStack // Stack for ints
{
int StackPointer = 0;
int[] StackArray; // Array of int
public void Push( int x ) // Input type: int
{
...
}
public int Pop() // Return type: int
{
...
}
...
}
Search WWH ::




Custom Search