Replace Global Variables With Shared Properties
Visual Basic .NET gives you a more object-oriented way to store global data.
by Deborah Kurata
VSLive! Orlando, September 17, 2002
Note: Deborah Kurata is presenting "Best Practices for OOP in VB.NET" at VBITS Orlando, Tuesday, September 17. This tip is from that session.
We know we are never supposed to use global variables, but there are times when you need one. You might want to store the user's name as the last updated user in every record the user changes, so after the user logs in you want to store the user's name "somewhere." Or you might want to read a connection string from a file and store it "somewhere" so you can use it whenever you need to connect to the database. That "somewhere" used to be a global variablebut with Visual Basic .NET, there is a more object-oriented way to store global data.
With Visual Basic .NET, you can declare properties or methods to be global using the Shared keyword. Shared indicates that the property or method is shared among all instances of the class.
For example, this code creates a shared UserName property in a User class:
Public Class User
Private Shared m_sUserName As String
Public Shared Property UserName() As String
Get
Return m_sUserName
End Get
Set(ByVal Value As String)
m_sUserName = Value
End Set
End Property
End Class
Any code in the application can set this property without creating an instance of the class. For example, after validating the login, the Login form could set this property based on the user's login entry:
User.UserName = txtUserName.Text
Notice how the class name was used to reference the property. You don't need to create an instance of the class to access any shared properties or methods.
Because no instance was created, any code in the application can access the property and it will retain its value. For example, use this code to display the name in a messagebox:
MessageBox.Show("Thank you " & User.UserName)
Using the Shared keyword gives you an easy way to store data that is needed globally throughout your application. I enjoyed having Shared this tip with you!
About the Author
Deborah Kurata is a consultant and cofounder of InStep Technologies, a consulting group that designs and develops object-oriented and component-based Windows applications. Reach Deborah at deborahk@insteptech.com.
|