Singleton constructor pattern

suggest change
public class SingletonClass
{
    public static SingletonClass Instance { get; } = new SingletonClass();

		private SingletonClass()
    {
        // Put custom constructor code here
    }    
}

Because the constructor is private, no new instances of SingletonClass can be made by consuming code. The only way to access the single instance of SingletonClass is by using the static property SingletonClass.Instance.

The Instance property is assigned by a static constructor that the C# compiler generates. The .NET runtime guarantees that the static constructor is run at most once and is run before Instance is first read. Therefore, all synchronization and initialization concerns are carried out by the runtime.

Note, that if the static constructor fails the Singleton class becomes permanently unusable for the life of the AppDomain.

Also, the static constructor is not guaranteed to run at the time of the first access of Instance. Rather, it will run at some point before that. This makes the time at which initialization happens non-deterministic. In practical cases the JIT often calls the static constructor during compilation (not execution) of a method referencing Instance. This is a performance optimization.

See the Singleton Implementations page for other ways to implement the singleton pattern.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Constructors and Finalizers:
* Singleton constructor pattern

Table Of Contents
17 Regex
19 Arrays
21 Enum
22 Tuples
24 GUID
27 Looping
36 Casting
38 Constructors and Finalizers
46 Methods
88 Events
92 Structs
104 Indexer
106 Stream
107 Timers
109 Threading
127 Caching
135 Pointers
147 C# Script