Blog

Creating Lazy - Singleton Class

By Mahadesh Mahalingappa Blogs | C# Language Sep 27, 2011
In this blog we will see how to create a Singleton Class using the Lazy<T> in C#.
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>(
                delegate
                {
                    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; }
        }
    }


COMMENT USING

PREMIUM SPONSORS

Hire Mobile & Web Developer on demand. 100% satisfaction. Try for 1 week or Money Back. Local and remote developers available all over USA.

Latest Blogs