-3

I am writing a simple program to understand the scope of global variable and timer.

Public Class Form1
    Dim gobalVar As Integer

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        globalVar = 0
    End Sub  

    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
        Messagebox.Show(">" + globalVar.ToString)
        globalVar = 1
        Messagebox.Show("<" + globalVar.ToString)

    End Sub
End Class

I set the timer to 5 seconds. so when the timer is trigger globalVar is 0, since it is set to 0 when the form is load, then after I set globalVar to 1, and the messagebox confirm it print <1 but the next time the timer is trigger the message box show >0, for some reason the globalVar is back to 0.

Shouldn't the globalVar be 1, since it is a global variable? am I declaring globalVar correctly as global variable in VB?

chrki
  • 6,143
  • 6
  • 35
  • 55
user7293420
  • 33
  • 2
  • 7

1 Answers1

4

Your global variable is named gobalVar but the variable you use in the timer method is globalVar. VB.Net is forgiving with variables that aren't declared. It is called Option Explicit and it is off in this case (I believe by default).

In your case, every time your timer ticks, the local variable globalVar is reinitialized to zero. Your actual global variable is never touched. Try putting Option Explicit On at the top of your file and you will then get a compiler error. It can also be set at the project level in the project properties screen.

Either that or fix the typo and rename your global variable (or update the timer ticks variable to match the typo).

Note also that this isn't really a global variable. It is an instance variable in your Form1 class. If you made another instance of the form, it would have its own instance of the variable.

To make it "truly" global (or rather the closest thing to it) either place it in a Module or make it Shared in your Form1 class.

Please see this answer for more information on "global" variables.

Community
  • 1
  • 1
pinkfloydx33
  • 11,863
  • 3
  • 46
  • 63