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













52 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
  8. It is amazing and wonderful to visit your site.Thanks for sharing this information,this is useful to me...
    Android Training in Chennai
    Ios Training in Chennai

    ReplyDelete
  9. 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.

    http://www.coepd.com/DotNet-Internship.aspx

    ReplyDelete
  10. This does not work when the second project is a Class Library and the class with the global variables is in the EXE Project.

    ReplyDelete
  11. The young boys ended up stimulated to read through them and now have unquestionably been having fun with these things.
    Hadoop Training in Chennai
    Hadoop Training in Bangalore

    ReplyDelete
  12. Thank you for allowing me to read it, welcome to the next in a recent article. And thanks for sharing the nice article, keep posting or updating news article.

    python training in chennai | python training in bangalore

    python online training | python training in pune

    python training in chennai | python training in bangalore

    python training in tambaram

    ReplyDelete
  13. You’ve written a really great article here. Your writing style makes this material easy to understand.. I agree with some of the many points you have made. Thank you for this is real thought-provoking content

    java training in chennai | java training in bangalore

    java online training | java training in pune

    ReplyDelete
  14. Thanks for splitting your comprehension with us. It’s really useful to me & I hope it helps the people who in need of this vital information. 
    python training in annanagar | python training in chennai

    python training in marathahalli | python training in btm layout

    python training in rajaji nagar | python training in jayanagar

    ReplyDelete
  15. I love the blog. Great post. It is very true, people must learn how to learn before they can learn. lol i know it sounds funny but its very true. . .

    java training in annanagar | java training in chennai

    java training in marathahalli | java training in btm layout

    java training in rajaji nagar | java training in jayanagar

    ReplyDelete
  16. After reading this web site I am very satisfied simply because this site is providing comprehensive knowledge for you to audience. Thank you to the perform as well as discuss anything incredibly important in my opinion. We loose time waiting for your next article writing in addition to I beg one to get back to pay a visit to our website in
    Click here:
    python training in Bangalore

    ReplyDelete
  17. Your good knowledge and kindness in playing with all the pieces were very useful. I don’t know what I would have done if I had not encountered such a step like this.
    Devops Training in pune

    Devops Training in Chennai

    Devops Training in Bangalore

    AWS Training in chennai

    AWS Training in bangalore

    ReplyDelete
  18. Wow it is really wonderful and awesome thus it is very much useful for me to understand many concepts and helped me a lot. it is really explainable very well and i got more information from your blog.

    rpa training in Chennai | rpa training in pune

    rpa training in tambaram | rpa training in sholinganallur

    rpa training in Chennai | rpa training in velachery

    rpa online training | rpa training in bangalore

    ReplyDelete
  19. Inspiring writings and I greatly admired what you have to say , I hope you continue to provide new ideas for us all and greetings success always for you..Keep update more information..

    rpa training in Chennai

    rpa training in anna nagar | rpa training in marathahalli

    rpa training in btm | rpa training in kalyan nagar

    rpa training in electronic city | rpa training in chennai

    rpa online training | selenium training in training

    ReplyDelete
  20. Your good knowledge and kindness in playing with all the pieces were very useful. I don’t know what I would have done if I had not encountered such a step like this.

    rpa training in Chennai | rpa training in pune

    rpa training in tambaram | rpa training in sholinganallur

    rpa training in Chennai | rpa training in velachery

    rpa online training | rpa training in bangalore

    ReplyDelete
  21. This is an awesome post.Really very informative and creative contents. These concept is a good way to enhance the knowledge.I like it and help me to development very well.Thank you for this brief explanation and very nice information.Well, got a good knowledge.
    Blueprism online training

    Blue Prism Training in Pune

    Blueprism training in tambaram

    ReplyDelete
  22. I am sure this post has helped me save many hours of browsing other related posts just to find what I was looking for. Many thanks!
    python training in tambaram
    python training in annanagar
    python training in OMR

    ReplyDelete
  23. I have been meaning to write something like this on my website and you have given me an idea. Cheers.

    java training in chennai | java training in USA

    selenium training in chennai

    ReplyDelete
  24. Thanks for the informative article. This is one of the best resources I have found in quite some time. Nicely written and great info. I really cannot thank you enough for sharing.
    Devops training in velachery

    ReplyDelete
  25. I have been meaning to write something like this on my website and you have given me an idea. Cheers.
    python training in rajajinagar
    Python training in btm
    Python training in usa

    ReplyDelete
  26. You’ve written a really great article here. Your writing style makes this material easy to understand.. I agree with some of the many points you have made. Thank you for this is real thought-provoking content
    Data science course in tambaram | Data Science course in anna nagar
    Data Science course in chennai | Data science course in Bangalore
    Data Science course in marathahalli | Data Science course in btm

    ReplyDelete
  27. Hello! This is my first visit to your blog! We are a team of volunteers and starting a new initiative in a community in the same niche. Your blog provided us useful information to work on. You have done an outstanding job.

    AWS Online Training | Online AWS Certification Course - Gangboard
    AWS Training in Chennai | AWS Training Institute in Chennai Velachery, Tambaram, OMR
    AWS Training in Bangalore |Best AWS Training Institute in BTM ,Marathahalli

    ReplyDelete
  28. UiPath Training in Bangalore by myTectra is one the best UiPath Training. myTectra is the market leader in providing Robotic Process Automation on UiPath
    robotic process automation training in bangalore

    ReplyDelete
  29. Thanks for the informative article. This is one of the best resources I have found in quite some time. Nicely written and great info. I really cannot thank you enough for sharing.
    SAP Abap On Hana Training

    Exchange Server Training

    Power BI Training

    ReplyDelete
  30. I am sure this post has helped me save many hours of browsing other related posts just to find what I was looking for. Many thanks!
    Datastage Training From India

    Cognos Training From India

    Abinitio Training From India

    ReplyDelete
  31. You’ve written a really great article here. Your writing style makes this material easy to understand.. I agree with some of the many points you have made. Thank you for this is real thought-provoking content
    Hyperion Essabse Selfplaced Videos

    Microsoft Azure Selfplaced Videos

    SCCM Selfplaced Videos

    ReplyDelete
  32. Excellent post!!!. The strategy you have posted on this technology helped me to get into the next level and had lot of information in it.
    python training in rajajinagar
    Python training in btm
    Python training in usa
    Python training in marathahalli

    ReplyDelete
  33. The knowledge of technology you have been sharing thorough this post is very much helpful to develop new idea. here by i also want to share this.
    DevOps online Training
    DevOps Training in USA

    ReplyDelete
  34. Your good knowledge and kindness in playing with all the pieces were very useful. I don’t know what I would have done if I had not encountered such a step like this.
    DevOps online Training

    ReplyDelete
  35. This is most informative and also this post most user friendly and super navigation to all posts... Thank you so much for giving this information to me.. 

    best rpa training in chennai |
    rpa training in chennai |
    rpa training in bangalore
    rpa training in pune | rpa online training

    ReplyDelete
  36. Hmm, it seems like your site ate my first comment (it was extremely long) so I guess I’ll just sum it up what I had written and say, I’m thoroughly enjoying your blog. I as well as an aspiring blog writer, but I’m still new to the whole thing. Do you have any recommendations for newbie blog writers? I’d appreciate it.

    AWS Interview Questions And Answers

    AWS Training in Bangalore | Amazon Web Services Training in Bangalore

    Amazon Web Services Training in Pune | Best AWS Training in Pune

    AWS Online Training | Online AWS Certification Course - Gangboard

    ReplyDelete

  37. Amazon Web Services (AWS) is the most popular and most widely used Infrastructure as a Service (IaaS) cloud in the world.AWS has four core feature buckets—Compute, Storage & Content Delivery, Databases, and Networking. At a high level, you can control all of these with extensive administrative controls accessible via a secure Web client.For more information visit aws online
    training

    ReplyDelete
  38. Really you have done great job,There are may person searching about that now they will find enough resources by your post
    java training in chennai | java training in bangalore

    java online training | java training in pune

    ReplyDelete
  39. Great post! I am actually getting ready to across this information, It’s very helpful for this blog.Also great with all of the valuable information you have Keep up the good work you are doing well.
    Data Science course in Chennai | Data science course in bangalore
    Data science course in pune | Data science online course
    Data Science Interview questions and answers

    ReplyDelete
  40. Thank you much for this tutorial; this is an informative and valuable blog. Visit for
    Hong Kong Honeymoon Packages

    ReplyDelete
  41. Excellent tutorial buddy. Directly I saw your blog and way of teaching was perfect, Waiting for your next tutorial.
    best rpa training institute in chennai | rpa training in velachery | rpa training in chennai omr

    ReplyDelete
  42. Good job in presenting the correct content with the clear explanation. The content looks real with valid information. Good Work

    DevOps is currently a popular model currently organizations all over the world moving towards to it. Your post gave a clear idea about knowing the DevOps model and its importance.

    Good to learn about DevOps at this time.
    devops training in chennai | devops training in chennai with placement | devops training in chennai omr | devops training in velachery | devops training in chennai tambaram | devops institutes in chennai | devops certification in chennai

    ReplyDelete