Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to declare a global variable

Status
Not open for further replies.

sjh

Programmer
Oct 29, 2001
263
US
Hi,
I would like to have a global variable g_sAppName. I tried declaring it inside my main form (shown below), but it is not recognized in other forms. How do I declare a global variable?

Public Class frmMain
Inherits System.Windows.Forms.Form

Public m_sAppTitle = "My .NET application"

___________________________
Many thanks,
Susie
 
You can create a Public Module and declare Public variables in it or Private variables with Public properties.

-Kris
 
Aren't modules a thing of the past? You can pass the object or whatever is it by value or by reference between forms using proper OOP methodolgy.
 
Modules are still there in VB.NET, but the correct OO way to do it would be to create an object using the Singleton design pattern.

You do a Singleton in VB.NET like this:
Code:
Imports System 

Public Class Singleton
  Private Shared myInstance As Singleton

  Private Sub New() 
  End Sub 
  
  Public Shared Function GetInstance() As Singleton
    If myInstance Is Nothing Then
      myInstance = New Singleton()
    End If
    Return myInstance
  End Function
End Class

Note that the constructor is private, so other callers are not able to directly create a new instance of this class. They have to go through the public Shared function called GetInstance. This returns them a copy of the internal instance (creating one the first time thru).

This way, everyone gets the same instance, which is what you want in a global variable.

Chip H.


If you want to get the best response to a question, please check out FAQ222-2244 first
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top