In this second article in his series, Peter Aitken explains how to use the Shared keyword with methods and events.
In the previous article I introduced the Shared keyword as it is used in object-oriented programming in VB.Net. I showed you how shared variables can be used to share data with all instances of a class, and to provide parameters for use by shared methods.
In this second and final article on the topic, I cover the other two uses of Shared: with methods and with events.
ADVERTISEMENT
Shared Methods
In most situations, class methods are called on an instance of the class. For example, here's a class with a non-shared method (sometimes called an instance method, because you must create an instance of the class to use the method).
No special keyword is required because methods are, by default, instance methods. This is a simple method that does nothing more than return one half of the passed argument.
Public Class SomeClass
Public Function HalfOf(ByVal x As Double) As Double
Return x / 2
End Function
End Class
To call the method, you first have to create an instance of the class:
Dim obj As New SomeClass
And then call the method:
y = obj.HalfOf(x)
By adding the Shared keyword to the method definition, you make it possible to call the method on the class name itself without the need to create an instance of the class. Here's the code for a class with a shared method:
Public Class SomeClass
Public Shared Function HalfOf(ByVal x As Double) As Double
Return x / 2
End Function
End Class
And here's how you can call it:
y = SomeClass.HalfOf(x)
A class can contain a mix of shared and instance methods. And, if you create an instance of the class, you can still call its shared methods on the instance. Be aware that a shared method cannot use the Me keyword to reference the current instance (since there may be no current instance), nor can it be defined with the Overridable, NotOverridable, or MustOverride keywords. Shared methods are public by default. You can overload shared methods in the usual manner.
A shared method can access shared variables in a class. It cannot, of course, access instance variables. I presented an example in the previous article when I discussed shared variables.
But, you may be thinking, what's the point? You may think that instantiating a class in order to call its methods is not a big deal. Or is it? Remember, each time you create a class instance, memory processor time and memory are required. Also, you need to keep track of your created instances and dispose of them when they are no longer needed. This may be a minor inconvenience in a small, simple program, but can rapidly add up in a larger development project.
Also, you may point out that a shared method has the identical functionality as a procedure in a Visual Basic module. This is 100% true, and it's the reason why VB.Net programmers rarely create classes that contain only shared methods. Rather, shared methods are almost always part of a class that contains other members including instance methods. The .Net framework itself has many classes, such as File, that contain shared methods. Note also that C# programmers do not have modules at their disposal and are more likely to turn to shared methods.
Shared methods are called static methods in C#, and are created using the static keyword. They work pretty much the same as shared methods in VB.Net. The primary difference is that a static method in a C# class cannot be accessed through a class instance, but only by using the class name.
Shared Events
The final use of the Shared keyword is with events. You can mark an event as Shared with the keyword as follows:
Public Shared Event SomeEvent()
There are two reasons for declaring an event as Shared. First, shared methods can raise only shared events (although instance methods can raise both shared and instance events). Second, shared events can be trapped from the class itself and not just from instances of the class. To illustrate, I will modify the IceCream class from before, so it has a shared method and raises that method when an instance of the class is created. The class code is shown here with the two new lines marked:
Public Class IceCream
' Constants for the available flavors
Public Const VANILLA = 1
Public Const CHOCOLATE = 2
Public Const STRAWBERRY = 3
Public Const COFFEE = 4
Private pFlavor As Integer
Public Shared Event NewIceCream()
'<-----new line
Public Sub New(ByVal flavor As Integer)
pFlavor = flavor
RaiseEvent NewIceCream()
' <----new line
End Sub
End Class
In the program that uses the class, you would create a handler for the event, such as this one:
Private Sub OnNewIceCream()
MsgBox("New ice cream created!")
End Sub
Then connect the handler to the event as usual. Typically, this is done in a Form_Load event.
Note that the AddHandler statement uses the class name, IceCream, rather than
the name of an instance. This has the effect of connecting the event handler to NewIceCream events raised by any and all instances of the IceCream class — just what we want in this situation.
Summing Up
Use of the Shared keyword in VB.Net gets some people scratching their heads, because it is used in several different contexts. As I have tried to show you in these two articles, the various ways that Shared is used — with methods, variables, and events — are not exactly the same but are definitely related. These are valuable programming techniques that you need in your toolbox if you want to progress beyond the basics with VB.Net object-oritned programming.