Trusted answers to developer questions

How to implement the singleton pattern in C#

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

The singleton design pattern is one of the most popular design patterns in the programming world. A singleton is a class that allows only a single instance of itself to be created.

Difference between singleton and conventional class
Difference between singleton and conventional class

In the code below, when getObj() is called for the first time, it creates a Singleton obj and returns the same obj after that. This example is not a thread-safe method; two threads running at the same time can create two objects for Singleton.


Non-thread safe

// This method is not thread-safe.
public sealed class Singleton
{
private static Singleton obj=null;
// private constructor.
private Singleton()
{
}
// public static method for creating a single instance.
public static Singleton getObj
{
get
{
if (obj==null)
{
obj = new Singleton();
}
return obj;
}
}
}

Note that Singleton obj is created according to the requirement of the user. This is called lazy instantiation.


Thread safe

// This method is thread-safe.
public sealed class Singleton
{
private static Singleton obj = null;
// mutex lock used forthread-safety.
private static readonly object mutex = new object();
Singleton()
{
}
public static Singleton getObj
{
get
{
lock (mutex)
{
if (obj == null)
{
obj = new Singleton();
}
return obj;
}
}
}
}

In the above code, a mutex lock is implemented for mutual-exclusion. Similarly, in the code below, a nested private class is implemented. This allows a single instance of Singleton when it is referenced for the first time in getObj() method.

public sealed class Singleton
{
private Singleton()
{
}
public static Singleton getObj
{
get
{
return Nested.obj;
}
}
// private nested class.
private class Nested
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested()
{
}
internal static readonly Singleton obj = new Singleton();
}
}

RELATED TAGS

c#
singleton
design pattern
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?