Post navigation

Implicitly type local variables in VB 9.0

I love this new feature of VB 9 (Orcas). It lets you declare local variables without explicitly declaring the type, but the compiler (and intelli-sense) will infer the type from the assignment. So it is STILL strongly typed (type safe). For example, these 2 statements are the same:

Dim aStr As String = “Test string”

Dim bStr = “Test string”

Take a look at the intelli-sense:

In both instances the IDE understood that the variables are strings, even though bStr was not explicitly declared “as string”. I like this because sometimes I declare a variable as an arraylist and then decide I want to use a generic collection or something else. This way I don’t have to go and change the type, I just change the assignment, so instead of:

Dim implicitArray = New ArrayList

I use

Dim implicitArray = New Generic.List(OfString)

And voila, I am done.

Remember, the variable is strongly typed i.e. it is not just declared as “object”.