See this site: http://www.yoda.arachsys.com/csharp/singleton.html
This is the basic singleton pattern in C#. It works but isn't thread safe.
// This is not thread safe! public sealed class Singleton { static Singleton instance=null; Singleton() { } public static Singleton Instance { get { if (instance==null) { instance = new Singleton(); } return instance; } } }
I chose the second version from that site, which uses a lock to ensure thread safety.
public sealed class Singleton { static Singleton instance = null; static readonly object padlock = new object(); Singleton() { } public static Singleton Instance { get { lock (padlock) { if (instance==null) { instance = new Singleton(); } return instance; } } } }
Note that both of these use lazy instantiation. That is, the singleton instance isn't created until the first time the Instance property is called.