Information Technology Reference
In-Depth Information
Declaring a Generic Class
Declaring a simple generic class is much like declaring a regular class, with the following
differences:
￿
Place a matching set of angle brackets after the class name.
￿
Between the angle brackets, place a comma-separated list of the placeholder strings that
represent the types, to be supplied on demand. These are called type parameters .
￿
Use the type parameters throughout the body of the declaration of the generic class to
represent the types that should be substituted in.
For example, the following code declares a generic class called SomeClass . The type param-
eters are listed between the angle brackets, and then used throughout the body of the
declaration as if they were real types.
Type parameters
class SomeClass < T1, T2 >
{ Normally, types would be used in these positions.
public T1 SomeVar = new T1();
public T2 OtherVar = new T2();
}
Normally, types would be used in these positions.
There is no special keyword that flags a generic class declaration. The presence of the type
parameter list distinguishes a generic class declaration from a regular class declaration.
Creating a Constructed Type
You cannot create class objects directly from a generic class. First, you need to tell the compiler
what actual types should be substituted for the placeholders (the type parameters). The com-
piler takes those actual types and creates a template from which it creates actual class objects.
To construct a class type from a generic class, list the class name and supply real types
between the angle brackets, in place of the type parameters. The real types being substituted
for the type parameters are called type arguments .
Type arguments
SomeClass< short, int >
Search WWH ::




Custom Search