Since I used to be a Java programmer, I used to write singletons in c# like this:

public class MySingleton {
 
      private static MySingleton instance;
      
      public static MySingleton Instance
      {
         get
         {
            if (instance == null)
            {
               lock(typeof(MySingleton))
               {
                  if (instance == null)
                  {
                     instance = new MySingleton();
                  }   	            
               }
            }
            return instance;
         }
 
      private MySingleton()
      {
            // do init
      }
}

Until I wanted to show a colleague the data & object factory site, a design patterns website specifically targeted at c# development.

Aparently, as stated here, there is a more elegant way of implementing a thread-safe, lazy instantiated singleton in .NET. You can just declare your instance field to be static and readonly, assign a new instance at the line where you declare it and it will be lazy-instantiated at runtime.

Like this:

public class MySingleton {
 
      private static readonly MySingleton instance 
                                          = new MySingleton();
      
      public static MySingleton Instance
      {
         get { return instance; }
      }
 
      private MySingleton()
      {
            // do init stuff
      }
}

Looks a lot better. But do both code snippets behave in exactly the same way? Before testing the differences myself, I decided to give my good friend Google a spin, and it came up with this interesting article by Alois Kraus.

Aparently it would not be wise to just convert all singletons in my projects to the ‘elegant’ .NET way :)