SoFunction
Updated on 2025-03-08

C# Singleton Pattern Example Tutorial

This article describes the implementation method of C# singleton pattern in an example form, and shares it for your reference. The specific implementation method is as follows:

Generally speaking,When looking at the global perspective of the application, if only one instance of the class is allowed to be generated, the singleton pattern can be considered.

1. Instant loading singleton mode

Assign an instance of the class to a static field of the class.

class Program
{
    static void Main(string[] args)
    {
      Logger log = ();
      ();
      ();
    }
}
public class Logger
{
    private static Logger logger = new Logger();
    private Logger(){}
    public static Logger GetInstance()
    {
      return logger;
    }
    public void WriteToFile()
    {
      ("The error was written to the file~~");
    }
}

2. Singleton mode for lazy loading

The class instance is not generated until the static method of the class is called.

public class Logger
{
    private static Logger logger = null;
    private Logger(){}
    public static Logger GetInstance()
    {
      if (null == logger)
      {
        logger = new Logger();
      }
      return logger;
    }
    public void WriteToFile()
    {
      ("The error was written to the file~~");
    }
}

3. Thread-safe singleton mode

Until the static method of the class is called, it is ensured that only one thread enters the instance of the generated class.

public class Logger
{
    private static Logger logger = null;
    private static object lockObj = new object();
    private Logger(){}
    public static Logger GetInstance()
    {
      lock (lockObj)
      {
        if (logger == null)
        {
          logger = new Logger();
        }
        return logger;
      }
    }
    public void WriteToFile()
    {
      ("The error was written to the file~~");
    }
}

Summarize:Private fields of static singleton type, private constructor, the method to obtain singleton is to form the three necessary elements of the singleton pattern. I hope this article will be helpful to everyone's C# programming.