Static Constructor in the Singleton Design Pattern

On MSDN I found two approaches for 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 this object for us before first use?

+3


source to share


1 answer


Can you use a static constructor of course. I don't know why you want to use it, just using the second example you showed, but you certainly could. It will be functionally identical to your second example, but it just requires more text input.



Note that your first example is not safe to use if the resource is being accessed from multiple threads, and the second is safe. In the first example, you will need to use lock

some other synchronization mechanism to prevent the possibility of creating multiple instances.

+4


source







All Articles