65.9K
CodeProject is changing. Read more.
Home

Singleton Pattern VB.NET using Static Variable

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.25/5 (4 votes)

May 23, 2012

CPOL
viewsIcon

59287

The most elegant implementation for VB.NET and safe as simple

Introduction

I have seen many implementations of the Singleton pattern. This one seems to be the most elegant for VB.NET and is as safe as simple.

Theory

Static Local Variables in VB.NET

In VB, a local variable marked as static, apart from usual local variable, continues to exist and retains its most recent value. Moreover, it is initialized only once and this operation is thread safe.

What it simply means is that while the first time property is accessed, the variable is defined and initialized with a value given. Every next call initialization and declaration is ignored and the variable is used as shared/static for this class and continues to exist for a lifetime of the class.

Singleton Pattern Implementation

Public Class Singleton

    Private Sub New()

    End Sub

    Public Shared ReadOnly Property GetInstance As Singleton
        Get
            Static Instance As Singleton = New Singleton
            Return Instance
        End Get
    End Property

End Class

Please do let me know if there are any pitfalls or if you have other ideas.