Implementing a Singleton Class The Right way

I was in Teched Africa Last week and during my session one of the Audience "Carl Mönnig" shared a nice feedback about the way I was Implementing Singleton Class so Decided to Share it with everyone for future usage

 

I did not like the singleton pattern you used in the Win8 LOB In Depth talk… It looked something like this:

 

public class MySingleton ()

{

      private MySingleton () {} //Private cstr

     

      private static MySingleton _instance ;

     

      public static MySingleton Instance {

            get {

                  if ( _instance == null )

                        _instance = new MySingleton ()

                  return _instance ;

            }};

}

 

This is too much code and it is not thread-safe when multiple threads call MySingleton.Instance at the same time. You need to add double-check locking to make it thread-safe.

 

Cleaner option:

 

public class MySingleton ()

{

      private MySingleton () {} //Private cstr

      public static readonly MySingleton Instance = new MySingleton ();

}

 

The class will be constructed the first time MySingleton.Instance is called and will be get-only because of readonly. This is also thread-safe without any locks (handled by the CLR). This is a Poor Man's singleton, because serious applications will have an IoC container to provide singletons.

 

Thanks for the double session – I picked up a few useful tips. Hopefully I am telling you something new and useful above in return J