Option Infer in VB9

Sun, February 18, 2007, 06:30 PM under dotNET | Orcas | LINQ
I will assume here that you have read the narrative to my C# post about local variable type inference and build on it to discuss the VB syntax.

The VB syntax for local variable type inference is:
Dim i = 3
Dim s = "hi"
Dim o = New SomeType()
...which the compiler generates as:
Dim i As Integer = 3
Dim s As String = "hi"
Dim o As New SomeType()
Note that for reference types, you are not really saving a lot of typing compared to C#. The example I used in that post was:
    Dim myCol = New Dictionary(Of Integer, SomeType)()
, which represents a saving of only one character in VB:
    Dim myCol As New Dictionary(Of Integer, SomeType)()
What is more important is that some VB developers will be thinking right now “So what? I could always type Dim o = whatever”. My answer is “Not if you turned Option Strict On”. Don’t forget what I wrote in the c# version: this is early binding. Like shown above, the compiler infers the type and generates it for you. At this point, the astute reader will have a question: “So if I turn off Option Strict, then what happens? The old behaviour or the new?”. To which my answer is “Excellent point, let’s talk about that :-)”.

There is a new option in VB9: Option Infer. Option Infer, like its cousins, can be turned on/off at the project level or at the code file level. If you have Option Strict Off, then whether a variable has the old behaviour or new is determined by the setting of Option Infer. This also means that, unlike c#, you can turn off local variable type inference even in the strongly typed world (by setting Option Strict to On and then Option Infer to off). I believe the default for new VB projects will be that Option Infer is On.

There is a good opportunity here for all that VB6 code you ported over to .NET land and did not want to revisit with Option Strict On. If you turn Option Infer On, the code that did work, will now work faster. The code that had issues, will still have issues (for that you must still turn option Strict On).

Anyway, back to our syntax, the following example shows how to get variable inference in the For Each case like I showed before in C#:
    Dim col As IEnumerable(Of SomeType) = New SomeCollectionType()
For Each a In col 'a is inferred by the compiler to be SomeType
a.MethodOnSomeType() 'intellisense here pops-up as expected
Next
In the code above, the variable a is inferred by the compiler to be SomeType. Of course, if you turn Option Infer Off, then you will get a compiler error even with Option Strict Off. The only way not to get a compiler error for variable a is to turn Option Explicit Off too but we know that is just mad.

More language features follow!
Comments are closed.