Click here to Skip to main content
Click here to Skip to main content

Singleton Pattern VB.NET using Static Variable

By , 24 May 2012
 

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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

EvgeniySu
Web Developer
Ukraine Ukraine
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
SuggestionSingletoneprotectorAspDotNetDev25 May '12 - 13:40 
GeneralRe: SingletonememberEvgeniySu26 May '12 - 9:10 
GeneralIt still needs more explanationmemberPIEBALDconsult25 May '12 - 8:39 
GeneralRe: It still needs more explanationmemberEvgeniySu26 May '12 - 9:32 
QuestionInstantiationmemberCtznkane24 May '12 - 8:33 
AnswerRe: InstantiationmemberPIEBALDconsult25 May '12 - 8:29 
GeneralMy vote of 1memberMarcus Kramer23 May '12 - 8:45 
GeneralRe: My vote of 1memberEvgeniySu23 May '12 - 11:15 
GeneralRe: My vote of 1memberkfsdavidt6424 May '12 - 3:25 
GeneralRe: My vote of 1memberEvgeniySu24 May '12 - 22:57 
QuestionGood, though...memberJose Menendez Póo23 May '12 - 8:37 
AnswerRe: Good, though...memberEvgeniySu23 May '12 - 11:16 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130516.1 | Last Updated 24 May 2012
Article Copyright 2012 by EvgeniySu
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid