Type inference occurs when a local variable is declared without an As clause and assigned a value. The compiler uses the type of the value as the type of the variable. For example, the following lines of code each declare a variable of type String.
' Using explicit typing.
Dim name1 As String = "Springfield"
' Using local type inference.
Dim name2 = "Springfield"
The following code demonstrates two equivalent ways to create an array of integers.
' 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}
You can use type inference to determine the type of a loop control variable. In the following code, the compiler infers that num is an Integer, because someNumbers2 is an array of integers.
Dim total = 0
For Each number In someNumbers2
total += number
Next
Local type inference can be used in Using statements to establish the type of the resource name, as the following example demonstrates.
Using proc = New System.Diagnostics.Process
' Insert code to work with the resource.
End Using
The type of a variable can also be inferred from the return values of functions, as the following example demonstrates. Both pList1 and pList2 are lists of processes.
' Using explicit typing.
Dim pList1() As Process = Process.GetProcesses()
' Using local type inference.
Dim pList2 = Process.GetProcesses()