Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c#
singleton
design pattern

How to implement the singleton pattern in C#

Educative Answers Team

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.

svg viewer
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;
    }
  }
}
Remember this above example is not thread-safe

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 ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring