Generic Type Inference

written by Ryan Olshan on Friday, December 30 2005

One of the cooler features I like in Generics is type inference. Type inference allows you to call a generic method just as you would a non-generic method using its method signatures as references to the type(s), instead of specifying the type(s).

VB.NET
Public Sub TestMethod1(Of T, U)(ByVal val1 As T, ByVal val2 As U)
   Response.Write("Value 1: {0}, Value 2: {1}", val1, val2)
End Sub

Public Function TestMethod2(Of T)(ByVal val As T) As T
   Return val
End Function

TestMethod1("Bob", 172)
' Same as TestMethod1(Of String, Integer)("Bob", 172)
TestMethod1(14, "Marry")
' Same as TestMethod1(Of Integer, String)(14, "Marry")
TestMethod2(46)
' Same as TestMethod2(Of Integer)(46)

C#
public void TestMethod1<T, U>(T val1, U val2)
{
   Response.Write("Value 1: {0}, Value 2: {1}", val1, val2);
}

public T TestMethod2<T>(T val)
{
   return val;
}

TestMethod1("Bob", 172);
// Same as TestMethod1<string, int>("Bob", 172)
TestMethod1(14, "Marry");
// Same as TestMethod1<int, string>(14, "Marry")
TestMethod2(46);
// Same as TestMethod2<int>(46)

Kick this post on .NET Kicks

Similar Posts

  1. What's wrong with this generic class?
  2. Generic Sub Classes
  3. Nullable Types

Post a comment