The generic method can use the type placeholder for parameters, the return, and within the body. The return type is a little confusing, because it appears before the declaration of the placeholder. This is also a little confusing to intellisense, which will try to match the return type to one declared outside the class. Be careful of unintended typos because of this.
If the type placeholder is used somewhere in the parameter list, then the compiler can infer the type based on the actual parameters. This is a really powerful feature that leads to some amazingly elegant code, as we'll see in some of the examples. But this type inference is limited only to methods, and only to types used in the parameter list. The compiler cannot infer the return type of a method, nor can it infer generic class parameters from its constructor, as you might expect. As we'll see later, you solve this problem using a generic factory.
Public Class ClassWithGenericMethod
Public Shared Function Method _
(Of T)(ByVal value As T) As T
Return value
End Function
End Class
Dim l As Integer
l = ClassWithGenericMethod _
.Method("Hello").Length
class ClassWithGenericMethod
{
public static T Method<T>
(T value)
{
return value;
}
}
int l;
l = ClassWithGenericMethod
.Method("Hello").Length;