Singleton pattern C#

A Singleton class in OOP allows only one instance of itself to be created. While a conventional class can have any number of instances created. Below is the thread-safe implementation of Singleton class.

using System;
namespace SingletonPattern
{
    // thread-safe way.
    public sealed class Singleton
    {
        private static Singleton obj = null;
        // mutex lock used for thread-safety.
        private static readonly object mutex = new object();
        private int var = 0;

        private Singleton()
        {
        }

        public static Singleton getObj
        {
            get
            {
                lock (mutex)
                {
                    //lazy loading..
                    if (obj == null)
                    {
                        obj = new Singleton();
                    }
                    return obj;
                }
            }
        }

        public void doSomething()
        {
            var += 1;
            Console.WriteLine($"Current Value: {var}");
        }
    }
}

Now, when we call the Singleton class object using getObj from anywhere, it’ll return the same instance of obj.

using System;

namespace SingletonPattern
{
    class Program
    {
        static void Main(string[] args)
        {
            Singleton instance = Singleton.getObj;
            instance.doSomething();
            instance.doSomething();
        }
    }
}

Output:

Current Value: 1
Current Value: 2

An example of a Singleton class can be a Database which returns only 1 instance of itself from wherever we connect to it.

How is it different from a Static class?

  1. A Singleton class can inherit other classes and can also implement interfaces.
  2. A Singleton can be initialized lazily or asynchronously and loaded automatically by the .NET Framework CLR when the program or namespace containing the class is loaded. While a static class is generally initialized when it is first loaded.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.