Information Technology Reference
In-Depth Information
Generic Methods
Unlike the other generics, a method is a member, not a type.
Generic methods can be declared in both generic and non-generic classes, structs, and
interfaces, as shown in Figure 19-10.
Figure 19-10.
Generic methods can be declared in generic and non-generic types.
Declaring a Generic Method
Generic methods, like the other generics, have a type parameter list and optional constraints.
Generic methods, like generic delegates, have two parameter lists, as follows:
-The
method parameter list
, enclosed in parentheses.
-The
type parameter list
, enclosed in angle brackets.
To declare a generic method, do the following:
-
Place the type parameter list immediately after the method name and before the
method parameter list.
-
Place the optional constraint clauses after the method parameter list.
Type parameter list
Constraint clauses
↓
↓
public void PrintData< S, T > (
S p
) where S: Person
{
↑
...
Method parameter list
}
■
Note
Remember that the type parameter list goes
after
the method name and
before
the method param-
eter list.