Information Technology Reference
In-Depth Information
Inferring Types
If you are passing parameters into a method, the compiler can sometimes infer from the types
of the
method parameters
the types that should be used as the
type parameters
of the generic
method. This can make the method calls simpler and easier to read.
For example, the following code declares
MyMethod
, which takes a method parameter of the
same type as the type parameter.
public void MyMethod <T> (T myVal) { ... }
↑
↑
Both are of type T
If you invoke
MyMethod
with a variable of type
int
, as shown in the following code, the
information in the type parameter of the method invocation is redundant, since the compiler
can see from the method parameter that it is an
int
.
int MyInt = 5;
MyMethod <int> (MyInt);
↑
↑
Both are ints
Since the compiler can infer the type parameter from the method parameter, you can omit
the type parameter (and its angle brackets) from the invocation, as shown here:
MyMethod(MyInt);