Information Technology Reference
In-Depth Information
Example of a Generic Method
The following code declares a generic method called ReverseAndPrint in a non-generic class
called Trivial . The method takes as its parameter an array of any type. Main declares three dif-
ferent array types. It then calls the method twice with each array. The first time it calls the
method with a particular array, it explicitly uses the type parameter. The second time, the type
is inferred.
class Trivial // Non-generic class
{
static public void ReverseAndPrint<T>(T[] arr) // Generic method
{
Array.Reverse(arr);
foreach (T item in arr) // Use type argument T.
Console.Write("{0}, ", item.ToString());
Console.WriteLine("");
}
}
class Program
{
static void Main()
{
// Create arrays of various types.
int[] IntArray = new int[] { 3, 5, 7, 9, 11 };
string[] StringArray = new string[] { "first", "second", "third" };
double[] DoubleArray = new double[] { 3.567, 7.891, 2.345 };
Trivial.ReverseAndPrint<int>(IntArray); // Invoke method
Trivial.ReverseAndPrint(IntArray); // Infer type and invoke
Trivial.ReverseAndPrint<string>(StringArray); // Invoke method
Trivial.ReverseAndPrint(StringArray); // Infer type and invoke
Trivial.ReverseAndPrint<double>(DoubleArray); // Invoke method
Trivial.ReverseAndPrint(DoubleArray); // Infer type and invoke
}
}
Search WWH ::




Custom Search