Simple Singleton Pattern in C#






4.85/5 (5 votes)
I'll be shot for posting this as an alternative, but I'm too curious for the answer.Shashank Bisen wrote: Ensure a class only has one instance.Provide a global point of access to it....As stated above, a singleton is a class that can be instantiated once, and only once.What is the...
I'll be shot for posting this as an alternative, but I'm too curious for the answer.
What is the benefit of being able to instantiate a singleton? AFAIK, it'd be used for lazy loading, otherwise one could simply create aShashank Bisen wrote:Ensure a class only has one instance. Provide a global point of access to it. ... As stated above, a singleton is a class that can be instantiated once, and only once.
static
class and be done with it. Or even a class with a private
constructor and some shared members. :)
There are also three examples on MSDN, including a "multithreaded" singleton: Implementing a singleton in C#[^]From MSDNAs is the case with all class types, the type information for a static class is loaded by the .NET Framework common language runtime (CLR) when the program that references the class is loaded. The program cannot specify exactly when the class is loaded. However, it is guaranteed to be loaded and to have its fields initialized and its static constructor called before the class is referenced for the first time in your program. A static constructor is only called one time, and a static class remains in memory for the lifetime of the application domain in which your program resides.