Thursday, April 21, 2011

Singleton in C#

Just went though the implementing singleton in c#.
http://msdn.microsoft.com/en-us/library/ff650316.aspx
In short the ideal code :


using System;

public sealed class Singleton
{
   private static volatile Singleton instance;
   private static object syncRoot = new Object();

   private Singleton() {}

   public static Singleton Instance
   {
      get 
      {
         if (instance == null) 
         {
            lock (syncRoot) 
            {
               if (instance == null) 
                  instance = new Singleton();
            }
         }

         return instance;
      }
   }
}


Things of note:

  • The instance is marked volatile. If its multithreaded it might as well be volatile.
  • This will not work in JAVA since double checking is broken problem in Java :
    http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html
  • C# ensures that static variables are initialized BEFORE you can use a property. 
  • Instance is created only when it is requested. This is lazy initialization. 
  • Because of lazy initialization we need another reference type (we use an object) to carry out the lock.
  • We really don't want anybody inheriting our data and messing with it ... so sealed. 


Enjoy!

No comments:

Post a Comment