O'Reilly logo

Microsoft® Visual Basic® .NET Programmer's Cookbook by Matthew MacDonald

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Use the Singleton Pattern

Problem

You want to ensure that only one copy of a class can be instantiated at once and provide global access to this instance.

Solution

Add a private constructor to the class and a shared variable that holds the singleton instance.

Discussion

The syntax for creating a singleton in languages that target .NET is quite a bit simpler than in many other languages, due to the way the common language runtime operates. The basic pattern is to add a shared variable that returns an instance of the singleton class, as shown here:

Public Class MySingleton Private Sub New() ' A private constructor ensures this class can't be created directly, ' except by code in this class. End Sub ' This shared member is available even without an instance ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required