How to enable/disable it
It is on by default, but you can set it by placing
Option Infer On|Off at the top of the code file. The option will apply to the whole document.
You can switch it on/off via the menu in Visual Studio:
Project > [Project] Properties > Compile Tab > Option infer
On|Off in the drop-down menu. The option will apply to the whole document.
All new projects
You can switch it On by default for all new Projects by selecting:
Tools > Options > Projects and Solutions > VB defaults > Option Infer
On|Off in the drop-down menu.
What is it?
Enables the use of local type inference in declaring variables.
What is type inference?
You can declare local variables without explicitly stating a data type. The compiler infers the data type of a variable from the type of its initialization expression.
Option Infer On:
vs. explicit type declaration:
Option Infer Off:
The compiler behavior with
Option Infer Off depends on the
Option Strict setting
which is already documented here.
Option Infer Off - Option Strict Off
All variables without explicit type declarations are declared as
Option Infer Off - Option Strict On
The compiler won´t let you declare a variable without an explicit type.
When to use type inference
Basically you can use type inference whenever it is possible.
However, be careful when combining
Option Infer Off and
Option Strict Off, as this can lead to undesired run-time behavior:
Anonymous types can only be declared with
Option Infer On.
They are often used when dealing with LINQ:
Option Infer Off
The compiler will either throw an error (with
Option Strict On)
or will consider
Option Strict Off).
Both cases will produce the outcome that you cannot use the anonymous type.
Numeric variables with decimal places will be infered as
Double by default:
If another type like
Decimal is desired the value which initialized the variable needs to be marked: