Variables

If we want to add a reset button to the counter program, declaring counter insdie the procedure for BtnClick will not work. A variable is only available in the procedure where it is delared, that is it is local to that procedure.

A global variable is one that is not declared inside a procedure or function. A global variable can be accessed, changed, or modified anywhere in the program. Variables that are declared inside a procedure or function are local: they can only be used inside the procedure or function where they are declared. We are going to modify the counter program by making counter global. The counter will be declared outside of the procedures, making it global. Write the code as shown below:

Public Class Form1
    Dim counter As Integer = 0
    Private Sub BtnCounter_Click(sender As Object, e As EventArgs) Handles BtnCounter.Click
        counter += 1
        Me.Text = counter
    End Sub

    Private Sub BtnReset_Click(sender As Object, e As EventArgs) Handles BtnReset.Click
        counter = 0
    End Sub

NEXT: Arithmetic Operations