Creating Lazy - Singleton Class

By Mahadesh Mahalingappa Sep 27 2011
In this blog we will see how to create a Singleton Class using the Lazy in C#.
    • Like
    • Love It
    • Awesome
    • Interesting
    • It's Okay
    • Thumbs Down
  • 5.5k
  • 0
Lazy<T> provides support for Lazy Initialization.

By Lazy Intialisation we mean that an object is not intialised until it is actually used. Below, I have shown how we can combine the Lazy<T> with the Singleton Pattern.

  public sealed class LazySingleton
        // Private object with lazy instantiation
        private static readonly Lazy<LazySingleton> instance =
            new Lazy<LazySingleton>(
                    return new LazySingleton();
            //thread safety first
                , System.Threading.LazyThreadSafetyMode.ExecutionAndPublication);

        private LazySingleton()
            // no public default constructor

        // static instance property
        public static LazySingleton Instance
            get { return instance.Value; }