Design Patterns

Implementing a Singleton pattern in C#

A Singleton is the combination of two essential properties:

Ensure a class only has one instance.
Provide a global point of access to it.

 public sealed class Singleton   
{
// Thread safe Singleton with fully lazy instantiation
private Singleton()
{
}
public static Singleton Instance { get { return Nested.instance; } }
private class Nested
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested()
{
}
internal static readonly Singleton instance = new Singleton();
}
}

Using Lazy type

 public sealed class Singleton  
{
private static readonly Lazy lazy =
new Lazy(() => new Singleton());
public static Singleton Instance { get { return lazy.Value; } }
private Singleton()
{
}
}

Leave a comment