Techniques - DevSource
DevSource: Microsoft Developer Resource DevSource Home Sponsored by Microsoft Home Add Ons Architecture Languages Techniques Using VS Forums
Home arrow Techniques arrow Like Mom Told You: Sharing is Nice!
Like Mom Told You: Sharing is Nice!
By Peter Aitken

Rate This Article: Add This Article To:

Like Mom Told You: Sharing is Nice!
( Page 1 of 2 )

The VB.NET Shared keyword can be mighty confusing. Peter Aitken demonstrates why and how to take advantage of it.

If you have worked much with VB.Net's object oriented programming, you have probably come across the Shared keyword. You may also have immediately reached for the aspirin, because this keyword is a source of confusion for many programmers. Used in different contexts, Shared means totally different things, so the headaches are perfectly understandable! In this is the first of a two-article series, I hope to reduce your need for aspirin while letting you improve your .Net programs by appropriate use of Shared.

Shared can be used as a modifier for methods, for variables, and for events. In brief, the use of Shared can be described as follows:

  • A shared method can be called directly from a class without having to create an instance of the class.
  • A shared variable is shared by all instances of the class.
  • A shared event is the only kind of event that can be raised by shared methods.
ADVERTISEMENT

This may sound like so much gobbledygook to you! Well, it did to me at first, too. Let's decipher what these definitions mean.

Shared Variables

A shared variable in VB.Net is, like a shared method, created using the shared keyword. It works quite differently, however. A shared variable is one that is shared by all instances of the class. This is different from the default kind of variable, called an instance variable, where each separate instance of the class has its own independent copy of the variable.

To declare a shared variable, use the shared keyword:

Shared Total As Long

Shared variables have private scope by default, but can be made public by including the Public keyword:

Public Shared Total As Long

A shared variable is, in effect, a single variable that is shared by all instances of its class. It can be very useful in situation where you want all instances of a class to always have access to the same value for a particular variable.

For example, banking application might define a class to keep track of individual savings accounts. When it comes time to calculate monthly interest, all accounts use the same interest rate. By making InterestRate a shared variable, you can set the value for one instance of the class and automatically have it used by all instances.

Note that the sharing of shared variables extends only within the current program. It does not extend to instances of the class that may exist in other programs.

You can use a shared variable to created a shared property. Define a variable with Private access, using the Shared keyword as well, then write a property procedure to provide access to it. One way that I have used this technique is to keep track of how many instances of a class exist. This is demonstrated in the VB.Net console application shown here. First there is the class InstanceCounter, whose code is as follows:

Public Class InstanceCounter

Private Shared pInstanceCount As Long

Public Sub New()
    pInstanceCount += 1
End Sub

Protected Overrides Sub Finalize()
    pInstanceCount -= 1
End Sub

Public ReadOnly Property InstanceCount() As Long
    Get
        Return pInstanceCount
    End Get
End Property

End Class

Note the following things about this class:

  • It has a private shared variable named pInstanceCount that hold the data of interest.
  • In the constructor (the sub New()), pInstanceCount is incremented by one. Thus, every time an instance of the class in created, the count goes up by one.
  • In the Finalize() procedure, pInstanceCount is decremented by one. When a class instance is destroyed, the count is maintained.
  • There is a read-only property procedure that provides public access to the value of pInstanceCount.

Here's the code for the remainder of the application:

Module Module1

Sub Main()

Dim ob1 As New InstanceCounter
Dim ob2 As New InstanceCounter
Dim ob3 As New InstanceCounter

Console.Write(ob1.InstanceCount)
Console.WriteLine()
Call Foo()
' Force garbage collection.
System.GC.Collect()
' Wait for the user to press enter.
Console.ReadLine()
Console.WriteLine(ob1.InstanceCount)
' Wait for Enter again.
Console.ReadLine()
End Sub

Private Sub Foo()
    Dim q As New InstanceCounter
    Console.WriteLine(q.InstanceCount)
    Console.WriteLine()
End Sub

End Module

Let's track what happens when this program runs:

  1. Three instances of the class InstanceCounter are created.
  2. The number of instances — 3 — is displayed by accessing the InstanceCount property of one of the class instances. It is ob1 in this example, but it could have been any of the three instances with the same results.
  3. The sub Foo() is called. Code in Foo() creates another, local, instance of InstanceCounter and displays the current instance count, which is now 4.
  4. Execution returns from Foo() to Main() which again displays the instance count. Because the instance that was created in Foo() has gone out of scope, and we have forced garbage collection to take place, the count is back to 3.

In addition to being shared by all instances of a class, shared variables are also available without creating an instance at all — in other words, by using just the class name. For example, here's a simple class definition with one shared variable:

Public Class SomeClass
    Public Shared Maximum As Integer
End Class

A program could set the value of this variable as follows:

SomeClass.Maximum = 50

Why would you bother doing this?



 
 
>>> More Techniques Articles          >>> More By Peter Aitken
 



Microsoft's Future: A Chat With Their CTO, Barry Briggs

Play Video >

All Videos >

Julia explores the Robotics Studio!

Read now >

Messages to Bill Gates!

Read now >

View Now
DevSource RSS FEEDS
XML Want an easy way to keep up with breaking tech news? And the Get DevSource headlines delivered to your desktop with RSS.