Home
VB.NET
Shared Keyword
This page was last reviewed on Jan 12, 2024.
Dot Net Perls
Shared. In VB.NET a Shared function is not part of an instance. Some functions and fields may be specific to an entire type, not an instance.
Function
The Shared modifier specifies that a function is meant for the entire type, not just a certain instance of it. Each instance has the same shared member.
An example. In the Widget class, we see a Public Shared Function and a Public Function. In Main, we can call Widget.Test() because Test() is a Shared function. No instance is required.
Sub
However We must instantiate Widget, with New Widget(), to call TestB(). The TestB() function is not Shared.
Info Shared fields can be accessed by Shared Functions. Regular Functions can access both Shared fields and also regular fields.
Thus This means that Shared functions have additional restrictions on what they can do.
Module Module1 Class Widget Public Shared Function Test() As Integer ' Cannot access regular fields. Return Integer.Parse("1") End Function Dim _value As String = "2" Public Function TestB() As Integer ' Can access regular fields. Return Integer.Parse(_value) End Function End Class Sub Main() ' Use Shared Function. Console.WriteLine(Widget.Test()) ' Use Non-Shared Function. Dim w As Widget = New Widget() Console.WriteLine(w.TestB()) End Sub End Module
1 2
Shared field. Here we have a Shared field called "_index." When multiple IndexObject instances are created in Main, the index field is shared between them all.
Module Module1 Class IndexObject Shared _index As Integer = 0 Public Sub Display() _index += 1 Console.WriteLine("INDEX: {0}", _index) End Sub End Class Sub Main() ' The index field is shared between objects. Dim test As IndexObject = New IndexObject() test.Display() Dim test2 As IndexObject = New IndexObject() test2.Display() End Sub End Module
INDEX: 1 INDEX: 2
Performance. The .NET runtime needs to evaluate instances before an instance function can be called. For this reason, Shared functions have a performance advantage.
Also In many implementations, instance functions are passed a reference to the instance as the first argument.
Summary. We saw an example of a Shared function and a regular function. Shared members, often called static members, are part of the type, not part of the type's instances.
Final notes. You can determine whether a function should be shared based on whether it acts upon specific instances or not. Shared functions have advantages and disadvantages.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jan 12, 2024 (edit).
Home
Changes
© 2007-2024 Sam Allen.