Freigeben über


Local Variable Type Inference

[Table of Contents] [Next Topic]

Local variable type inference is a feature in VB 9.0 where you can use the Dim keyword instead of explicitly specifying the type of a variable.  If Option Explicit is on, the VB 9.0 compiler makes the type of the variable match the type of the right side of the assignment.  There are places when using VB 9.0 where we must do type inference when declaring variables; there is no other way, so we must cover this topic here.

This blog is inactive.
New blog: EricWhite.com/blog

Blog TOCLINQ query expressions (and many standard query operators) return a type of IEnumerable(Of T) for some type T.  When using LINQ, it is often convenient to make the type parameter be an anonymous type.  An anonymous type's name is automatically generated by the compiler, but hidden from the program.  If you write a query expression that creates an anonymous type, then the results of the query expression are an IEnumerable of the anonymous type.  To declare a variable to hold the results of such a query expression it is necessary to use type inference.  Anonymous types are introduced further on in this tutorial.

Simple Example of Type Inference

The following are a few local variable declarations with initializers:

Dim i As Integer = 5
Dim s As String = "Hello"
Dim d As Double = 1.0
Dim orders As Dictionary(Of Integer, String) = New Dictionary(Of Integer, String)()

The above code is precisely the same as:

Dim i = 5
Dim s = "Hello"
Dim d = 1.0
Dim orders = New Dictionary(Of Integer, String)()

Note that you could use this same syntax with Option Strict Off, however, I recommend never using that option.  And with Option Strict On, the above code will cause a compiler error.  So setting Option Strict On and Option Infer On, you are allowed to use the above syntax, and the variables will still be strongly typed.

Option Strict On
Option Infer On

Module Module1
Sub Main()
Dim i = 5
Dim s = "Hello"
Dim d = 1.0
Dim orders = New Dictionary(Of Integer, String)()
End Sub
End Module

Consider the following code:

Option Strict On
Option Infer On

Module Module1
Sub Main()
Dim t = 1
Console.WriteLine(t.GetType())
End Sub
End Module

When run, this code produces:

System.Int32

Using type inference tells the compiler to take the type on the right hand side, and use that type for the variable.  It specifically does not mean VARIANT, or Object.  The variables are strongly typed; the only difference is that the compiler is able to deduce the type from the initializer.

The topic on anonymous types shows examples where it is necessary to use type inference.

[Table of Contents] [Next Topic] [Blog Map]