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


  1. We at COEPD glad to announce that we have introduced Dot Net Technologies Internship Programs (Self sponsored) for professionals who want to have hands on experience. This program is available in COEPD Hyderabad premises which is accompanied by IT Companies. It is intelligently dedicated to our firm participants predominantly acknowledging and appreciating the fact that they are on the path of making a career in Dot Net Technologies discipline. We assume Object-Oriented Programming concepts and teaches C#.NET, ADO.NET which helps the interns to build database-driven Web applications and Web Sites successfully. This internship is designed to gain theoretical knowledge and also hands-on practice and practical know-how to master the nitty-gritty of the Dot Net developer profession. More than a training institute, COEPD today stands differentiated as a mission to help you "Build your dream career" - COEPD way.