views:

118

answers:

1

I would like to use VB9 but am not sure what syntax to use to say that I want a variable to be statically typed as in C#'s:

var foo = new Whatever();

In previous versions of VB:

Dim foo = New Whatever()

created a dynamically typed variable.

Is there a way to get static typing without actually writing the type in VB9?

+2  A: 

Yes, you can control this behaviour through the Option directives at the beginning of each file or in the project settings:

Option Strict Off

' The following is dynamically typed: '
Dim x = "Hello"


Option Strict On
Option Infer On

' This is statically typed: '
Dim x = "Hello"

It's best-practice to set Option Strict On as the default for all your projects (can be done in the options dialog). This guarantees the same typing behaviour as in C#. Then, if you need dynamic typing, you can disable the setting selectively on a per-file basis by using the directive mentioned above.

Konrad Rudolph
Ahh, too bad it's on a per-file basis. I wish I could do it on a per-variable basis.
Frank Krueger
"Option Infer On" just allows the practice... you can still dim X as Object or Dim X As Integer
Rory Becker