SoFunction
Updated on 2025-03-07

C# creates a singleton in multiple ways

Regarding why a singleton needs to be created? I won’t introduce it here, specifically Baidu Knows.

About C# Create a singleton step or condition

1. Declare static variables;

2. Private constructor (cannot be instantiated)

3. Methods to create instances statically; as for my Singleton here, I am sealed, just to prevent inheritance, it is actually enough to have a private constructor, it is just for code readability.

The first common way to create singletons:

/// <summary>
 /// Unsafe single case /// </summary>
 public sealed class Singleton
 {
  private static Singleton _Singleton;
  private Singleton() { }
  public static Singleton GetSingleton()
  {
   if (_Singleton == null)
   {
    _Singleton = new Singleton();
   }
   return _Singleton;
  }
 }

Note: Why is it an unsafe singleton? Multiple objects may be new when accessing multiple threads...

The second way to create a singleton:

/// <summary>
 /// (Multi-threaded) safe single case /// </summary>
 public sealed class Singleton
 {
  private static Singleton _Singleton;
  private static readonly object obj = new object();
  private Singleton() { }
  public static Singleton GetSingleton()
  {
   if (_Singleton == null)
   {
    //Lock protection, it can ensure that the instance value is created once under multithreading.  The disadvantage is that every time a singleton is obtained, it is necessary to make a judgment, and the locks and unlocks involved are more resource-intensive.    lock (obj)
    {
     if (_Singleton == null)
     {
      _Singleton = new Singleton();
     }
    }

   }
   return _Singleton;
  }
 }

Note: It was born to solve the problem of unsafe instances created in the first method above.

The third way to create a singleton:

/// <summary>
 /// Read-only single case /// </summary>
 public sealed class Singleton
 {
  private static readonly Singleton instance = new Singleton();
  private Singleton() { }
  public static Singleton Instance
  {
   get
   {
    return instance;
   }
  }
 }
/// <summary>
 /// Based on the above read-only singleton = automatic attribute read-only singleton (synonym sugar) /// </summary>
 public sealed class Singleton
 {
  private Singleton() { }
  public static Singleton Instance { get; } = new Singleton();
 }

Note: Read-only attribute => With the help of readonly attribute, instance is only initialized once, which also achieves the effect of a singleton. Before the first sentence is executed by referring to the function, the instance has actually been assigned, not expected. The object is created only when accessing the Instance variable.

The fourth way to create a singleton:

/// <summary>
 /// Add a static constructor to Singleton. /// </summary>
 public sealed class Singleton
 {
  public static readonly Singleton instance = new Singleton();
  private Singleton()
  {
   ("Initialize 1!");
  }
  static Singleton()
  {
  }
  public static Singleton Instance
  {
   get { return instance; }
  }
 }

Note: In order to solve the problem that the instance has been initialized before executing the first sentence code.

The fifth way to create a singleton:

/// <summary>
 /// Create singletons with Lazy, by default, thread-safe /// </summary>
 public sealed class Singleton
 {
  private static readonly Lazy<Singleton> instance = new Lazy<Singleton>(() => new Singleton());//
  private Singleton() { }
  public static Singleton Instance
  {
   get
   {
    return ;
   }
  }
 }
// Post a definition of the above Lazy<T> s=new Lazy<T>() parameter;  // Summary:  // Initialize a new instance of class `1.  When lazy initialization   // When it occurs, use the specified initialization function and initialization mode.  
  // Parameters:  // valueFactory:
  // Delegation called to generate delayed initialization values ​​is a required parameter  //
  // isThreadSafe:
  // true if you want this instance to be used by multiple threads at the same time; false         //Make this instance only be used by one thread at a time.  public Lazy(Func&lt;T&gt; valueFactory, bool isThreadSafe);

The above is the detailed content of various ways to create singletons in C#. For more information about creating singletons in C#, please pay attention to my other related articles!