VB.Net Variables

In VB.Net a Variable can be dependent and independent variables. It can be a symbolic name associated with any value and can be used to store any data types like String, Boolean, Integer, Byte, etc.

In this tutorial, we'll help you understand what is the purpose of using variables, how to create and use them in your program.

Independent Variables
Let's take a look at the following code below to illustrate a usage of independent variables.
Public Class Form1
    Dim GuestName As String = "Jhon Doe"
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        MessageBox.Show("Hello " & GuestName & "! How are you today?", "Greetings")
    End Sub
End Class

This line of code simply means that we declare a String variable named GuestName and set its value to "Jhon Doe".
Dim GuestName as String = "Jhon Doe"

When the button on the form is clicked this line of code is executed. This means that it will show a message box saying "Hello Jhon Doe! How are you today?".
MessageBox.Show("Hello " & GuestName & "! How are you today?", "Greetings")
You might be asking how but this is how the code was interpreted. The GuestName variable will grab the value we declared which is "Jhon Doe" and put it in the message instead.

Dependent Variables
Let's take a look at the following code below to illustrate the usage of dependent variables.
Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim RoomWidth As Integer = InputBox("Please input the width of the Room:", "Width")
        Dim RoomLength As Integer = InputBox("Please input the length of the Room:", "Length")         
        Dim RoomArea As Integer = RoomLength * RoomWidth
        MessageBox.Show("The total area is " + RoomArea.ToString())
    End Sub
End Class

The above codes means that when the user clicks the button, it will prompt the user to input the Length and Width of a Room. Calculate the Room's Area and show the total area to the user.

The variables RoomWidth and RoomLength are considered as independent variables. While the variable named RoomArea is considered as the dependent variable. Because it will require the user to enter values to both variables otherwise, there will be an execution error.

The line of code below calculates the value entered in the RoomLength and RoomWidth variables.
Dim RoomArea As Integer = RoomLength * RoomWidth

The line of code below will simply display the result value of the variable named RoomArea.
MessageBox.Show("The total area is " + RoomArea.ToString())
You might be asking why there's a .ToString() after the RoomArea. That is because if we combine a strings with a variable containing numbers in a MessageBox we need to convert it to string.

0 comments: