Search code examples
c#design-patternssingletonstatic-constructor

Static constructor in Singleton design pattern


On MSDN I found two approaches to creating a singleton class:

public class Singleton {
   private static Singleton instance;
   private Singleton() {}
   public static Singleton Instance {
      get {
         if (instance == null)
            instance = new Singleton();
         return instance;
      }
   }
}

and

 public sealed class Singleton {
   private static readonly Singleton instance = new Singleton();
   private Singleton(){}
   public static Singleton Instance {
      get { return instance; }
   }
}

My question is: can we just use a static constructor that will make for us this object before first use?


Solution

  • Can you use the static constructor, sure. I don't know why you'd want to use it over just using the second example you've shown, but you certainly could. It would be functionally identical to your second example, but just requiring more typing to get there.

    Note that your first example cannot be safely used if the property is accessed from multiple threads, while the second is safe. Your first example would need to use a lock or other synchronization mechanism to prevent the possibility of multiple instances being created.