Understanding Generics—Omission of Type Parameters
Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio
Omission of Type Parameters
When you invoke generic methods such as Swap<T>, you can optionally omit the type parameter if
(and only if) the generic method requires arguments, as the compiler can infer the type parameter
based on the member parameters. For example, you could swap two System.Boolean types as so:
// 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);
However, if you had another generic method named DisplayBaseClass<T> that did not take any
incoming parameters, as follows:
static void DisplayBaseClass<T>() { Console.WriteLine("Base class of {0} is: {1}.", typeof(T), typeof(T).BaseType); }
you are required to supply the type parameter upon invocation:
static void Main(string[] args) { ... // Must supply type parameter if // the method does not take params. DisplayBaseClass<int>(); DisplayBaseClass<string>(); // Compiler error! No params? Must supply placeholder! // DisplayBaseClass(); ... }
Figure 10-1 shows the current output of this application.

Figure 10-1. Generic methods in action
Currently, the generic Swap<T> and DisplayBaseClass<T> methods have been defined within the
application object (i.e., the type defining the Main() method). If you would rather define these members
in a new class type (MyHelperClass), you are free to do so:
public class MyHelperClass { public static void Swap<T>(ref T a, ref T b) { Console.WriteLine("You sent the Swap() method a {0}", typeof(T)); T temp; temp = a; a = b; b = temp; } public static void DisplayBaseClass<T>() { Console.WriteLine("Base class of {0} is: {1}.", typeof(T), typeof(T).BaseType); } }
Figure 10-1. Generic methods in action
Notice that the MyHelperClass type is not in itself generic; rather, it defines two generic methods.
In any case, now that the Swap<T> and DisplayBaseClass<T> methods have been scoped within a new
class type, you will need to specify the type’s name when invoking either member, for example:
MyHelperClass.Swap<int>(ref a, ref b);
Finally, generic methods do not need to be static. If Swap<T> and DisplayBaseClass<T> were
instance level, you would simply make an instance of MyHelperClass and invoke them off the object
variable:
MyHelperClass c = new MyHelperClass(); c.Swap<int>(ref a, ref b);
|

