Mark Pringle - Wednesday, December 07, 2022
Singleton is a creational design pattern that ensures that only one class instance will be created while providing a global access point to this instance. This pattern ensures application-wide common functionality because only a single class instance can exist.
Use this pattern when it does not make sense to instantiate a new object or when resources are too expensive to instantiate.
Since design patterns are reusable solutions to problems, it is crucial to address the problem and solution for the Singleton design pattern.
The preceding raises another question. What is the difference between a static class and a Singleton since both can be invoked without instantiation and can be created to provide a central point of access, meaning there's only one instance and one way to access it?

There are various ways of implementing the Singleton pattern in C#. We will create a lazy-loaded, thread-safe example using Visual Studio's Console App template in this example. The Console App template code below uses .NET 6. Remember that the project template generated for new .NET 6 console apps has recent C# features that simplify the code you need to write for a program. So, the Program.cs file may look different if you are using .NET 5 or below.
To create a lazy-loaded, thread-safe Singleton, do the following:
LearnSingleton.LetsPlay();
public sealed class LearnSingleton
{
//Create a private static variable to hold a reference to the single created instance
//Initialized with null for lazy instantiation
//Ensures that only one instance of the object is created
private static LearnSingleton? instance = null;
//Locking ensures that all reads occur logically after the lock is acquired
private static readonly object padlock = new object();
private LearnSingleton()
{
}
//Create a public static property which will return only a single instance of the singleton class
//Expose the class as public so that it can be used by other code.
public static LearnSingleton Instance
{
get
{
//Locking ensures that all reads occur logically after the lock is acquired
lock (padlock)
{
//Assign a new instance of the singleton class
//Use compound assignment and null-coalescing operators
instance ??= new LearnSingleton();
return instance;
}
}
}
//Add a sample test method to see that this code has been called
public static void LetsPlay()
{
Console.WriteLine("LearnASPNET.com is Cool. Singleton.");
}
}
When the console is started without debugging...
