Shared Function Use Cases in VB .NET

Shared functions or Share methods in VB (Visual Basics).NET are similar to Static functions in C#. The use case of the Shared function will be discussed here. Examples are Factory Method, Helper functions, Logger class and Access Control, etc.

Factory Methods

In the Class property and methods can be used outside by creating instants or objects. However, the Shared keyword mentioned function can be used outside the class name only. A common function of the application is to create a class and reuse the named factory Method.

Public Class Employee
    Public Property Name As String

    ' Factory method
    Public Shared Function Create(name As String) As Employee
        Dim emp As New Employee()
        emp.Name = name
        Return emp
    End Function
End Class

Configuration Management

App configuration makes it read-only with a shared function is useful for making common database connections all over the application.

Public Class AppConfig
    Public Shared ReadOnly Property DatabaseConnectionString As String
        Get
            Return "Server=myServer;Database=myDB;User Id=myUser;Password=myPass;"
        End Get
    End Property
End Class

Logging

Accessing the Logger function anywhere in the application shared function can be used for logging the status of an application.

Public Class Logger
    Public Shared Sub Log(message As String)
        ' Code to log message
        Console.WriteLine($"Log: {message}")
    End Sub
End Class

Access Control

Shared functions also can be used in access control logic for admin and user login.

Public Class Admin
    Private Shared _adminCount As Integer

    Public Shared Sub AddAdmin()
        _adminCount += 1
    End Sub

    Public Shared Function GetAdminCount() As Integer
        Return _adminCount
    End Function
End Class