Tuesday, November 6, 2012

Static variable in Visual Basic

Static variable in Visual Basic

at all cost. Now that I told you not to use them, I’ll show you how they work and how come there are bad.

First of all, a static variable could be only being use inside a sub or function. They could not be a member of a Class or Module. Here is an example and honestly a big mistake:

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        Static iNumber As Integer = 0
        iNumber = iNumber + 1
        Me.Text = iNumber
    End Sub

A Static variable is a variable set one time in one place in your computer. That variable is not located in the function. That means the static variable stays even if the function ends. The Function doesn’t clean or clear the Static variable iNumber here in this example. So here you could keep mistaken value.
A second mistake here is the equal zero. Because your static variable iNumber is already created, it won’t reapply zero in that static variable. In fact, that first line in your function will simple is ignored and iNumber will simply change to 2, 3, 4….

A static variable is kind of available everywhere and is not saved for one single class or method. I could be used anywhere in your project or any instance. Maybe you want to use a static viable to share a value from one function to another. Well is not really had to use a simple global variable or pass a value in a function by argument? At least you have more control.

You are using thread in your program? Fine! Think about the delegate and invoke functions. There are there to read and change value between more sophisticated programs.


Microsoft Visual Studio Pro 2012 (released on September 2012)
Download sample project : SampleStatic.zip