Visual Basic .NET Language Declaring a Variable


In VB.NET, every variable must be declared before it is used (If Option Explicit is set to On). There are two ways of declaring variables:

  • Inside a Function or a Sub:
Dim w 'Declares a variable named w of type Object (invalid if Option Strict is On)
Dim x As String 'Declares a variable named x of type String
Dim y As Long = 45 'Declares a variable named y of type Long and assigns it the value 45
Dim z = 45 'Declares a variable named z whose type is inferred
           'from the type of the assigned value (Integer here) (if Option Infer is On)
           'otherwise the type is Object (invalid if Option Strict is On)
           'and assigns that value (45) to it 

See this answer for full details about Option Explicit, Strict and Infer.

  • Inside a Class or a Module:

These variables (also called fields in this context) will be accessible for each instance of the Class they are declared in. They might be accessible from outside the declared Class depending on the modifier (Public, Private, Protected, Protected Friend or Friend)

Private x 'Declares a private field named x of type Object (invalid if Option Strict is On)
Public y As String 'Declares a public field named y of type String
Friend z As Integer = 45 'Declares a friend field named z of type Integer and assigns it the value 45

These fields can also be declared with Dim but the meaning changes depending on the enclosing type:

Class SomeClass
    Dim z As Integer = 45 ' Same meaning as Private z As Integer = 45
End Class

Structure SomeStructure
    Dim y As String ' Same meaning as Public y As String
End Structure