Friday, November 9, 2012

Global Variables in Visual Basic .NET

Global Variables in Visual Basic .NET

Everything you need to know about Global Variable for VB.NET in this single Post.


Everything you need to know about Global Variable for VB.NET in this single Post. First of all, I am not here to debate whatever you should use or not Global Variables. In fact, no one cares and neither than me.  Many have their reasons on why not to use them while other says that we should use them because we need them.


Anyway, if you are here, is because you want to learn how to use them or wish to have an opinion on global variables. Please take a look on the project sample I made especially for this post.


I suggest you to download the project sample; it would be easier to understand. Because I am not good in English and my background is not computer science.  Sorry if I express myself differently that you.


One thing I want to say and we have to know is that a global variable is available everywhere. Unfortunately, global variable doesn’t exist that way in Visual Basic .NET. (Same for C#). Only to make this post easier to read, I will always use the term global variable even if in VB is not considered a Global Variable.
Global Variable, say it! Global Variable. Say it again Global Variable.

Two ways to make a global variable

With a Module like Module1.vb, the variable iOne :


Module Module1
    Public iOne As Integer
End Module



This is a second way, using a class named Class1, the other global variable is iTwo. If want want to make iTwo act like a global variable, we need to use the word shared. In C#, the equivalent is static.


Public Class Class1
    Public Shared iTwo As Integer
End Class



Do not mix the word static in C# with Static in other programming language. It might not be the same thing. Always stay in .NET (VB or C#).


I made a previous post about shared functions. I haven’t spent a lot of time explaining everything. If you read it, you might have an idea on what is a shared function or shared variable.


I finally made a form1 with 2 Labels and 2 buttons.



Public Class Form1
    Private WithEvents oTimer As Timer 'I cheat: don't use this to refresh your form
    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        Me.Text = "Form1 from GlobalVariable"
        oTimer = New Timer 'I cheat: don't use this to refresh your form

        With oTimer
            .Interval = 1000
            .Start()
        End With
    End Sub
    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        Module1.iOne = Module1.iOne + 1
        Label1.Text = Module1.iOne
    End Sub

   Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
        Class1.iTwo = Class1.iTwo + 1
        Label2.Text = Class1.iTwo
    End Sub

    Public Shared Sub add_Class1()
        ' there is a difference between public and public shared
        ' public is available but limited to current project
        ' public shared is extended to the solution (many projects)
        Class1.iTwo = Class1.iTwo + 1
    End Sub
    Public Shared Sub add_Module1()
        ' there is a difference between public and public shared
        ' public is available but limited to current project
        ' public shared is extended to the solution (many projects)
        Module1.iOne = Module1.iOne + 1


    End Sub

#Region "oTimer Events"
    Private Sub refreshMe() Handles oTimer.Tick
        Label1.Text = Module1.iOne  'I cheat: don't use this to refresh your form
        Label2.Text = Class1.iTwo  'I cheat: don't use this to refresh your form
        Me.Refresh()
    End Sub
#End Region
End Class



Believe me, if you make a single project with Module1, Form1 and Class1. You will not see the difference between the two types of global variable. They will acts like Global variable and you have the right to say it.


Global Variable, say it! Global Variable. Say it again Global Variable.


If you run the program, I won’t need to explain how the code works; you will notice how what the buttons do.



The limits of a global variable.


The real thing is when you have 2 projects or more. I have project GlobalVariables and project SecondProject.

Under SecondProject, I have another Form1 (form1.vb). Here is the code:
Public Class Form1

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        Me.Text = "Form1 from SecondProject"
        Button1.Text = "display Form 1 from GlobaVariable"
        Button2.Text = "+1 to Module1.iOne from GlobaVariable"
        Button3.Text = "+1 to Class1.iTwo from GlobaVariable"

        'GlobalVariable.Class1.iTwo = 100


    End Sub

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        Dim oForm1 As GlobalVariable.Form1
        Try
            oForm1 = New GlobalVariable.Form1
            oForm1.Show()

        Catch ex As Exception

        End Try

    End Sub

    Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
        GlobalVariable.Form1.add_Module1()

    End Sub

    Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) Handles Button3.Click
        GlobalVariable.Form1.add_Class1()
    End Sub
End Class



When you run the code and display the Form1 from project SecondProject, here is what you will get:


  Press the first button to bring the other Form1

If you press Button1 or Button2 , it will add 1 to each global variable from the project GlobalVariable. If you press any of the 2 other button from Form1 of the second project you will see that the counter add 1 to each global variables.






Everything is working but looks very carefully something: You can’t call Module1 from the second project. That is something you have to know. You just can’t.
Only when a variable (or function) is shared, it can be seen elsewhere.

Please note that the only way to access my global variable in my 1st project from my 2nd project is with shared function or shared variable.

Now that you read my post, I hope you liked it. I hope you know or remember the range of your global variables.


Global Variable, say it! Global Variable. Say it again Global Variable.


I am not here to tell you to use them or not. I haven’t written this post to debate if global variable are good or not. Neither if we could call them global or not.

I searched the web before writing this post, I haven’t seen any post like mine. Truly, many ask the question on the difference on public or global variable, or any between static of global but all the time, the information is incomplete or not good because some people are mixing C++, VB6 and newer language like C# and VB.NET.

If you liked this post or have a comment, write something or help me completed it. Share your impression. (I will moderate it anyway).

If you like this post, leave a comment or share it.

Download the sample project: GlobalVariable.zip
Use the same Visual Studio than mine: Visual Studio 2010 Professional
Get the latest version available : Visual Studio Professional with MSDN 2012


Reference: other post I found weak, incomplete or inspired me:

C/C++ related:

.NET related:








About 

I invite you to visit my blog for more articles and leave a comment. Check Technologies represents more than 10 years .... Computer and computer aided design.


235 Adrien-Provencher
Beloeil, (Québec), J3G 0C8, Canada
Tel : 514-705-7690
emal: info@checktechno.ca













9 comments:

  1. The most difficult features other programs don't even attempt are converted, such as LINQ, embedded XML, parameterized properties, local shared variables, On Error Goto statements, event handling, complex Case statements, API calls, and more.

    Don't take our word for it. Download a Free Trial Copy Today at www.vbconversions.com and check it out for yourself.


    vb to c# converter

    ReplyDelete
  2. wow, very detail for your article, its help me for try this tips, thanks mate ASP.NET

    ReplyDelete
  3. Programming is very interesting and creative thing if you do it with love. Your blog code helps a lot to beginners to learn programming from basic to advance level. I really love this blog because I learn a lot from here and this process is still continuing.
    Love from Pro Programmer

    ReplyDelete
  4. Such a like for easy explain the program for Visual basic .net using learn for vb applications. That can be variable platform for the vb.net programming language.

    Dotnet Training in Chennai

    ReplyDelete
  5. Very Nice Blog I like the way you explained these things.
    Indias Fastest Local Search Engine
    CALL360
    Indias Leading Local Business Directory

    ReplyDelete
  6. brilliant article that I was searching for. Helps me a lot
    call360 is Fastest local search Engine we have 12 years of experience in online industery, in our Search Engine we offer,
    more than 220 categories and 1 Million Business Listing most frequently search categories
    are Money exchange Chennai and Bike mechanic Chennai,
    we deliver 100% accure data to users & 100% Verified leads to our
    registered business vendors and our most popular categories are
    AC mechanic chennai,
    Advertising agencies chennai
    catering services chennai

    ReplyDelete
  7. brilliant article that I was searching for. Helps me a lot.
    We are one of the Finest ladies hostel near OMR and our
    womens hostel in adyar is secure place for working womens
    we provide home based food with hi quality, our hostel located very near to Adyar bus depot.
    womens hostel near Adyar bus depot, we are one of the best and experienced
    womens hostel near omr

    ReplyDelete