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:
Dim someVar = 5
someVar.GetType.ToString() '--> System.Int32
someVar = "abc"
someVar.GetType.ToString() '--> System.String
Anonymous Type
Anonymous types can only be declared with Option Infer On
.
They are often used when dealing with LINQ:
Dim countryCodes = New List(Of String)
countryCodes.Add("en-US")
countryCodes.Add("en-GB")
countryCodes.Add("de-DE")
countryCodes.Add("de-AT")
Dim q = From code In countryCodes
Let split = code.Split("-"c)
Select New With {.Language = split(0), .Country = split(1)}
Option Infer On
The compiler will recognize the anonymous type:
Option Infer Off
The compiler will either throw an error (with Option Strict On
)
or will consider q
as type object
(with Option Strict Off
).
Both cases will produce the outcome that you cannot use the anonymous type.
Doubles/Decimals
Numeric variables with decimal places will be infered as Double
by default:
Dim aNumber = 44.11 '--> Will be treated as type `Double` by the compiler
If another type like Decimal
is desired the value which initialized the variable needs to be marked:
Dim mDecimal = 47.11D '--> Will be treated as type `Decimal` by the compiler