5.7. Type Inference

One really handy aspect of generic methods is their ability to examine the types of incoming arguments and infer which method should be invoked. This eliminates the need to explicitly specify type arguments when calling a generic method. Consider the following method declaration and corresponding calls:

[VB code]
Public Sub InferParams(Of I, J)(ByVal val1 As I, ByVal val2 As J)
    Console.Out.WriteLine("I: {0}, J: {1}", val1.GetType(), val2.GetType())
End Sub

InferParams(Of Int32, String)(14, "Test")
InferParams("Param1", 3939.39)
InferParams(93, "Param2")
[C# code]
public void InferParams<I, J>(I val1, J val2) {
    Console.Out.WriteLine("I: {0}, J: {1}", val1.GetType(), val2.GetType());
}

InferParams<int, string>(14, "Test");
InferParams("Param1", 3939.39);
InferParams(93, "Param2");

This example declares a generic method that accepts two type parameters and provides three examples of calls to that method. The first call provides explicit type arguments. In this case, the types of the supplied parameter must match the types specified in the type parameter list. The next two examples both successfully call the InferParams() method without supplying any type arguments. They both use type inference, where the type is inferred from the types of the supplied arguments.

Leveraging this mechanism makes sense in most situations. However, in instances where you've overloaded a method, you may encounter some degree of ambiguity. Suppose you were to add the following overloaded ...

Get Professional .NET 2.0 Generics now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.