C# Singleton Pattern

The singleton pattern is an effective way to limit the existence of a class to a single instance.  Example areas where this pattern are beneficial would be a global context for an application, global application settings, or a global logging solution.

1 public class Singleton { 2 3 // Constructor is made private in order to avoid 4 // other code from creating an instance of the 5 // class. 6 private Singleton() {} 7 8 // A private variable holds the single instance 9 // to the class. 10 private static Singleton m_instance; 11 public static Singleton Instance { 12 get { 13 // If the singleton private variable 14 // has not yet been initialized with 15 // an instance of the singleton class, 16 // the singleton should be created and 17 // returned. Otherwise, the previously 18 // created singleton should be returned. 19 if (m_instance == null) 20 m_instance = new Singleton(); 21 22 return m_instance; 23 } 24 } 25 }

A common misusage of this pattern would be a class filled with static methods and variables. While this is technically a singleton, if the object is required to keep state, it is best to be left as a non-static class with a single instance.  The primary advantage is is to allow for interfacing and potential future instancing if the class were to grow beyond it’s single instance.

Another common problem is instantiating the singleton class is by using a static constructor.  While this does effectively create a singleton, if the singleton where to throw an exception during creation, the static constructor would always throw the exception rendering any static variables or methods on the class useless.  So, care must be taken if a static constructor is to be used.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s