The singleton pattern has fallen out of favour in recent times, the preference being towards using IoC in it’s place, but it’s still useful. I’m not going to go in depth into coding samples for this pattern as there’s an excellent article “Implementing the Singleton Pattern in C#” which covers the subject well.
A simple thread safe implementation taken from the aforementioned article is
public sealed class Singleton { private static readonly Singleton instance = new Singleton(); static Singleton() { } private Singleton() { } public static Singleton Instance { get { return instance; } } }
Note: The private constructor is included as the intention is for the user to use the Instance property to interact with the Singleton instance and not allow creating a new Singleton directly.
System.Lazy has been around since .NET 4.0 and it offers a threadsafe means to implement lazy loading/initialization. So now we can rewrite the above Singleton class with lazy loading
public sealed class Singleton { private static readonly Lazy<Singleton> instance = new Lazy<Singleton>(() => new Singleton()); private Singleton() { } public static Singleton Instance { get { return instance.Value; } } }