How to Use "VB.NET" "DIM" Statements to Decalre Variables in Visual Basic
In VB.NET, Microsoft has their priorities right and Option Explicit the default. This is the option that requires any variable you use in your code to be declared first. But you can declare all kinds of things with the Dim statement.
Since VB .NET is 'strongly typed' now, Microsoft doesn't recommend variable prefixes anymore, even though you still see them in a lot of code. In other words, you used to be encouraged to name an Integer variable something like intMyVariable to make it clear that the variable was intended to be used an integer.
But that was when variables were all of type Variant (which could be any type). Since VB.NET variables are all of specific types, the prefix is unnecessary now.
Option Explicit
Even before VB.NET, programming gurus have been telling us that it's a best practice to make sure that you declare all of your variables in a program. In VB6, you could get the compiler to help you by adding the Option Explicit statement to flag undeclared variables. But in VB.NET, Option Explicit is now the default. (Actually, it's Option Explicit On, but if you just enter Option Explicit, the IDE enters the word 'On' for you.) If you use the 'Off' parameter, however, you get this result:
Option Explicit Off ... Console.WriteLine("var1 is {0}", VarType(var1))
Which gives you ...
var1 is Object
Initialization and Dim
In VB.NET, variables can be declared and initialized on a single line ...
Dim myVar As String = "This is a string."
They can also be initialized as more things:
- Values from the command line
Dim MyString As String = Command()
Note: To test this using Visual Studio, which is not a command line environment, set command line values by selecting Project > Properties > Debug to enter a command line argument.
- System defined values
Dim TodayDate As DateTime = Today()
- Arrays of mixed objects
Dim myObjectArray() As Object = _ {3.14159, System.Math.Log10(365), "Whatever"} For Each obj In myObjectArray Debug.WriteLine(obj) Next
Note: The brackets enclose what is called an initializer list idiom.
- Instantiation of New objects
The New keyword invokes a constructor for the object.
Dim MyObjects As Object() = _ New Object() {1, 2, DateTime.Today, "George"}
- Multiple Variable Declaration
VB 6 would let you code this line:
Dim var1, var2, var3 As String
But only var1 would actually be a String. In VB.NET, the result is entirely different:
Dim var1, var2, var3 As Date MsgBox( _ "var1 type is: " & VarType(var1) & vbCrLf & _ "var2 type is: " & VarType(var2) & vbCrLf & _ "var3 type is: " & VarType(var3) _ )
All three are "Type 7" - Date in VB.NET.