型の推論は、As 句なしで宣言されたローカル変数に値が代入される場合に行われます。コンパイラは、変数の型として値の型を使用します。たとえば、次の各コード行は、String 型の変数を宣言しています。
' Using explicit typing.
Dim name1 As String = "Springfield"
' Using local type inference.
Dim name2 = "Springfield"
次のコードは、整数の配列を作成する 2 種類の同等の方法を示します。
' Using explicit typing.
Dim someNumbers1() As Integer = New Integer() {4, 18, 11, 9, 8, 0, 5}
' Using local type inference.
Dim someNumbers2 = New Integer() {4, 18, 11, 9, 8, 0, 5}
型の推論を使用して、ループ制御変数の型を決定できます。次のコードでは、someNumbers2 が整数の配列なので、コンパイラは number が Integer であると推論します。
Dim total = 0
For Each number In someNumbers2
total += number
Next
次の例で示すように、ローカル型の推論を Using ステートメントで使用して、リソース名の型を設定できます。
Using proc = New System.Diagnostics.Process
' Insert code to work with the resource.
End Using
次の例で示すように、関数の戻り値から変数の型を推論することもできます。pList1 と pList2 はどちらも、プロセスのリストです。
' Using explicit typing.
Dim pList1() As Process = Process.GetProcesses()
' Using local type inference.
Dim pList2 = Process.GetProcesses()