Free mag vol1 | Page 412

CHAPTER 9  COLLECTIONS AND GENERICS The output looks like this: ***** Fun with Custom Generic Methods ***** Before swap: 10, 90 You sent the Swap() method a System.Int32 After swap: 90, 10 Before swap: Hello There! You sent the Swap() method a System.String After swap: There Hello! The major benefit of this approach is that you have only one version of Swap() to maintain, yet it can operate on any two items of a given type in a type-safe manner. Better yet, stack-based items stay on the stack, while heap-based items stay on the heap! Inference of Type Parameters When you invoke generic methods such as Swap, you can optionally omit the type parameter if (and only if) the generic method requires arguments because the compiler can infer the type parameter based on the member parameters. For example, you could swap two System.Boolean values by adding the following code to Main(): // Compiler will infer System.Boolean. bool b1 = true, b2 = false; Console.WriteLine("Before swap: {0}, {1}", b1, b2); Swap(ref b1, ref b2); Console.WriteLine("After swap: {0}, {1}", b1, b2); Even though the compiler is able to discover the correct type parameter based on the data type used to declare b1 and b2, you should get in the habit of always specifying the type parameter explicitly: Swap(ref b1, ref b2); This makes it clear to your fellow programmers that this method is indeed generic. Moreover, inference of type parameters works only if the generic method has at least one parameter. For example, assume you have the following generic method in your Program class: static void DisplayBaseClass() { // BaseType is a method used in reflection, // which will be examined in Chapter 15 Console.WriteLine("Base class of {0} is: {1}.", typeof(T), typeof(T).BaseType); } In this case, you must supply the type parameter upon invocation: static void Main(string[] args) { ... // Must supply type parameter if 351