Variable Declaration in Visual Basic .Net
A variable is a name of the storage area which can be manipulated in a program. A variable is an identifier which can be changed or it is programmer dependent.
Before we use a variable in a VB.Net program the variable must be declared. Every variable in a Visual Basic program should have a data type which tells the compiler which data is going to store in that variable.
We have already discussed the basic data types that VB.Net provides.
Declaring a variable in VB.Net
In Visual Basic .Net the keyword Dim is used to declare a variable and allocate storage.
The syntax of variable declaration in VB.Net is as follows.
[ < attributelist> ] [ accessmodifier ] [[ Shared ] [ Shadows ] | [ Static ]] [ ReadOnly ] Dim [ WithEvents ] variablelist
attributelist: It specifies the attributes to be applied to a declared programming element. To use multiple attributes the comma is used for separation.
accessmodifier: It indicates the access level of a programming element such as a variable, constant, class or an enumeration.
The access modifier keywords in VB.Net are Public, Private, Protected, Friend, Protected Friend.
Shared: It is an optional part which is used declare a shared variable. A shared variable is not associated with any specific instance of a class or structure. It is available to all instance of the class or structure.
Shadows: It is also an optional part and is used to indicate that the variable re-declares and hides an identically named element, or set of overloaded elements, in a base class.
Static: A static variable can retain its value even when after the termination of the procedure where it is declared. This is an optional part of the variable declaration.
ReadOnly: The keyword ReadOnly is used to declare a variable as read only, not the write permission. It is also an optional part.
WithEvents: It is an optional part that specifies that the variable is used to respond to events raised by the instance assigned to the variable.
VariablesList: It is the list of variables that to be declared.
Dim name As String Dim num As Integer Dim average As Double
Variable Initialization in VB.Net
The process of assigning values to a variable is called the variable initialization.
In VB.Net the equal sign (=) is used for variable initialization.
variable_name = value;
In VB.Net we can assign values to a variable at the time of declaration or in the running time.
Variable initializing at the time of declaration
Dim a As integer = 10
Variable initializing after the declaration
Dim a As integer a = 10
Variable initializing at run time
Dim a As integer a = b + 10
We can also accept user values directly into a variable as shown below.
Dim limit As Integer limit = Console.ReadLine()