VB.NET Shared Function

The VB.NET programming language

In your VB.NET programs, some functions and fields may be conceptually specific to an entire type, not an instance of the type. The Shared modifier can be used to specify that a function is meant for the entire type, not just a certain instance of it.

This VB tutorial shows how to use the Shared modifier. Shared members are not part of a type instance.

Example

Note

This program introduces a Widget class. In the Widget class, we see a Public Shared Function, and also a Public Function. In the Main subroutine, we can call Widget.Test() because Test() is a Shared function; no instance is required. However, we must instantiate Widget, with New Widget(), to call TestB(). The TestB() function is not Shared.

Program that uses Shared function [VB.NET]

Module Module1

    Class Widget
	Public Shared Function Test() As Integer
	    ' Cannot acccess 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

Output

1
2

Fields. Fields, such as the _value field above, are also Shared or not Shared. Shared fields can be accessed by Shared Functions only, but regular Functions can access both Shared fields and also regular fields. This means that Shared functions have additional restrictions on what they can do.

Performance

Performance optimization

The .NET Runtime needs to evaluate instances before an instance function can be called. For this reason, Shared functions (static in the C# language) have a tiny performance advantage. In many implementations, instance functions are passed a reference to the instance as the first argument.

Summary

We looked at a simple example of a Shared function and also a regular function in the VB.NET language. Shared members, typically called static members in C-like languages, are part of the type, not part of the type's instances. They have certain advantages and also disadvantages, but you can determine whether a function should be shared based on whether it acts upon specific instances or not.

VB.NET Tutorials
.NET