SoFunction
Updated on 2025-03-07

C# singleton pattern implementation method

Singleton mode is probably the easiest of all design modes. If you are asked during an interview, which design modes you are familiar with, the first one you may answer is singleton mode.

The implementation of singleton mode is divided into two types: hungry and lazy. The former is instantiated immediately when the static constructor is executed, and the latter is instantiated when the first time it is needed during the program execution. Both have their own applicable scenarios, and the implementation method is very simple. The only issue to consider during design is: thread safety needs to be ensured during instantiation.

Hungry Man Style

The implementation of the Hungry Man style is very simple, instantiating it immediately in a static constructor:

public class Singleton
{
  private static readonly Singleton _instance;
  static Singleton()
  {
    _instance = new Singleton();
  }

  public static Singleton Instance
  {
    get
    {
      return _instance;
    }
  }
}

Note that to ensure singletonity, you need to use the readonly keyword to declare that the instance cannot be modified.

The above writing method can be abbreviated as:

public class Singleton
{
  private static readonly Singleton _instance = new Singleton();
  public static Singleton Instance
  {
    get
    {
      return _instance;
    }
  }
}

Herenew Singleton() It is equivalent to instantiating in a static constructor. In C# 7, you can further abbreviate it as follows:

public class Singleton
{
  public static Singleton Instance { get; } = new Singleton();
}

Just one sentence of code is done. This writing method is instantiated in the default static constructor. If it is a hungry man-style requirement, this implementation is the easiest. Someone will ask if there will be thread safety issues, and if multiple threads are called at the same time, multiple instances will be instantiated. No, because CLR ensures that all static constructors are thread-safe.

Note that you cannot write this:

public class Singleton
{
  public static Singleton Instance => new Singleton();
}

// Equivalent to:public class Singleton
{
  public static Singleton Instance
  {
    get { return new Singleton(); }
  }
}

This will result in a new instance being created for each call.

Lazy style

Lazy singleton implementation needs to consider thread safety issues. Let’s first look at a classic thread-safe single-column implementation code:

public sealed class Singleton
{
  private static volatile Singleton _instance;
  private static readonly object _lockObject = new Object();

  public static Singleton Instance
  {
    get
    {
      if (_instance == null)
      {
        lock (_lockObject)
        {
          if (_instance == null)
          {
            _instance = new Singleton();
          }
        }
      }
      return _instance;
    }
  }
}

When searching for C# singleton mode online, most of them use lock to ensure thread safety writing. This is the classic standard singleton mode writing. No problem, I feel relieved. Make an instance empty judgment inside and outside the lock, double insurance is enough to ensure thread safety and singletonity. But this way of writing seems to be too troublesome and easy to write incorrectly. As early as C# 3.5, I had a better way of writing, using Lazy<T>.

Sample code:

public class LazySingleton
{
  private static readonly Lazy<LazySingleton> _instance =
    new Lazy<LazySingleton>(() => new LazySingleton());

  public static LazySingleton Instance
  {
    get { return _instance.Value; }
  }
}

Call example:

public class Program
{
  public static void Main()
  {
    var instance = ;
  }
}

Use Lazy<T> to delay the instantiation of an object until it is first called, create and obtain an instance by accessing its Value property, and reading the Value property of a Lazy<T> instance will only execute instantiation code once, ensuring thread safety.

Wish you a happy coding!

The above is the detailed content of the implementation method of the c# singleton model. For more information about the c# singleton model, please pay attention to my other related articles!