Thursday, August 23, 2007 12:00 AM
bart
Visual Basic 9.0 Feature Focus - Implicitly Typed Local Variables
Welcome to my first post of the Visual Basic 9.0 Feature Focus blog series. In this post, we'll cover Implicitly Typed Local Variables, a feature also known as Local Variable Type Inference in the C# 3.0 world. So, what's it? Consider the following fragment in VB 8.0:
Dim i As Integer = 123
Dim s As String = "Bart"
Dim d As Dictionary(Of String, List(Of Integer)) = New Dictionary(Of String, List(Of Integer))
As you can see, there's quite some verbosity in the code fragment above. Why do we have to tell the compiler i is an integer if the right-hand side of the expression does the same (123 is an integer after all). Similar remarks hold true for the string s and especially for the (complex) Dictionary in the last line of code. Right, that last line could be abbreviated to
Dim d As New Dictionary(Of String, List(Of Integer))
But still, the verbosity is there for the other cases. What if you could write the following instead?
Dim i = 123
Dim s = "Bart"
Dim d = New Dictionary(Of String, List(Of Integer))
To show that you don't use any of the type information, take a look at the IntelliSense for say s:
That looks pretty much like the IntelliSense for a String variable, isn't it? That's because s is still known to be a string by the compiler, you don't lose any of the type information: the type of the local variable is inferred. Visual Basic 9.0 has one thing more than the C# 3.0 feature counterpart, which is an option to enable/disable this type inference mechanism: Option Infer.
For new projects, this option will be on by default. You can also set this option application-wide through the project properties Compile tab:
If you put Option Infer to Off, you'll get the following result:
The objects look as if they are typed at System.Object, but in reality you're switching to late binding right now:
If you want to keep Option Infer On but you'd like to have a variable to be late bound for some reason, you can use the following:
That is, declare the variable As Object. Needless to say so, late binding will only work if Option Strict is set to Off.
You might wonder whether this feature is so important. The answer is that Implicitly Typed Local Variables are optional in most cases, but in one scenario the use of it is mandatory: when you're using anonymous types, a feature I'll blog about later on in this series.
Happy coding!
Del.icio.us |
Digg It |
Technorati |
Blinklist |
Furl |
reddit |
DotNetKicks
Filed under: VB 9.0