Overloaded methods are often used to perform similar operations on different types of data. To understand the motivation for generic methods, let’s begin with an example (Fig. 20.1) that contains three overloaded DisplayArray
methods (lines 23–31, lines 34–42 and lines 45–53). These methods display the elements of an int
array, a double
array and a char
array, respectively. Soon, we’ll reimplement this program more concisely and elegantly using a single generic method.
The program begins by declaring and initializing three arrays—six-element int
array intArray
(line 10), seven-element double
array doubleArray
(line 11) and five-element char
array charArray
(line 12). Then, lines 14–19 output the arrays.
When the compiler encounters a method call, it attempts to locate a method declaration that has the same method name and parameters that match the argument types in the method call. In this example, each DisplayArray
call exactly matches one of the Display-Array
method declarations. For example, line 15 calls DisplayArray
with intArray
as its argument. At compile time, the compiler determines argument intArray
’s type (i.e., int[]
), attempts to locate a method named DisplayArray
that specifies a single int[]
parameter (which it finds at lines 23–31) and sets up a call to that method. Similarly, when the compiler encounters the DisplayArray
call at line 17, it determines argument double-Array
’s type (i.e., double[]
), then attempts to locate a method named DisplayArray
that specifies a single double[]
parameter (which it finds at lines 34–42) and sets up a call to that method. Finally, when the compiler encounters the DisplayArray
call at line 19, it determines argument charArray
’s type (i.e., char[]
), then attempts to locate a method named DisplayArray
that specifies a single char[]
parameter (which it finds at lines 45–53) and sets up a call to that method.
Study each DisplayArray
method. Note that the array element type (int
, double
or char
) appears in one location in each method—the method header (lines 23, 34 and 45). Each foreach
statement header (lines 25, 36 and 47) uses var
to infer the element type from the method’s parameter. If we were to replace the element types in each method’s header with a generic name (such as T
for “type”), then all three methods would look like the one in Fig. 20.2. It appears that if we can replace the array element type in each of the three methods with a single “generic type parameter,” then we should be able to declare one DisplayArray
method that can display the elements of any array. The method in Fig. 20.2 will not compile, because its syntax is not correct. We declare a generic DisplayArray
method with the proper syntax in Fig. 20.3.