Using variables

We have seen string variables and numeric variables, and will see object variables in subsequent notes.

Before you start coding in VB, you should plan which variables you will create. This is part of your internal planning (as opposed to the external description).

Remember that variables store values that will change during the execution of the program. There are no hard and fast rules, but, if you plan to refer to a value at more than one point in a program, it is probably a good idea to save it in a variable. Consider. for example, this demonstration program.

I could have written it using variables:

   Dim a As Single = Csng(TextBox1.Text)
   Dim b As Single = Csng(TextBox2.Text)
   lblAdd.Text = CStr(a + b)
   lblSub.Text = CStr(a - b)
   lblMult.Text = CStr(a * b)
   lblDiv.Text = CStr(a / b)
or without using variables:
   LblAdd.Text = CStr(Csng(TextBox1.Text) + Csng(TextBox2.Text))
   LblSub.Text = CStr(Csng(TextBox1.Text) - Csng(TextBox2.Text))
   LblMult.Text = CStr(Csng(TextBox1.Text) * Csng(TextBox2.Text))
   LblDiv.Text = CStr(Csng(TextBox1.Text) / Csng(TextBox2.Text))

Both of these do the same thing -- you cannot tell which approach the demonstration program uses.

In the first, the program begins by storing the values in two variables (a and b), and these are used in the subsequent statements. In the second, the values of the numbers in the TextBoxes are extracted and converted to integers each time they are referenced.

The first is six instructions long, but I find it clearer -- easier for me to read and understand. It would also execute faster, but that is of no concern with such a short program.

In general, do not try to cut down on the number of variables you create as you are learning programming. Everything that changes during execution -- things the user inputs, the program calculates or the program displays -- is a candidate for a variable. Having a lot of variables might make your program a bit longer than it has to be, but it will be clearer.

In debugging programs that use variables, it is helpful to use pencil and paper to keep track of the value of each of your variables as execution progresses from one statement to the next.


Disclaimer: The views and opinions expressed on unofficial pages of California State University, Dominguez Hills faculty, staff or students are strictly those of the page authors. The content of these pages has not been reviewed or approved by California State University, Dominguez Hills.