Why Singleton Class sealed in C#

Why Singleton Class sealed in C#?

In this article, I am going to discuss Why Singleton Class Sealed in C# with examples. Please read our previous article before proceeding to this article where we discussed the Singleton Design Pattern in C# with an example. As we already discussed we need to use the Singleton design pattern in C# when we need to ensure that only one instance of a particular class is available at any given point of time for the entire application. 

At the end of this article, you will understand why do we need to use the sealed keyword in the singleton class as we already have a private constructor within the class which will restrict the class for further inheritance.

Let’s understand why Singleton class is Sealed in C# with one example.

Let us understand why Singleton class Sealed in C# with examples. First, create the Singleton class without using the sealed keyword. We also create another class with the name DerivedSingleton and then Inherits it from the singleton class as shown below.

namespace SingletonDemo
{
    public class Singleton
    {
        private static int counter = 0;     
        private static Singleton instance = null;  
        public static Singleton GetInstance
        {
            get
            {
                if (instance == null)
                    instance = new Singleton();
                return instance;
            }
        }  
        private Singleton()
        {
            counter++;
            Console.WriteLine("Counter Value " + counter.ToString());
        }    
        public void PrintDetails(string message)
        {
            Console.WriteLine(message);
        }
    }

    public class DerivedSingleton : Singleton
    {

    }
}

At the moment, you will get the following compilation error. Error CS0122 ‘Singleton.Singleton()’ is inaccessible due to its protection level

The above error is because of the private constructor that we have in the Singleton class. Now you might be thinking that as we have a private constructor within the class so it is not possible to derive this class, then why do we need to apply the sealed keyword to the Singleton class.

Let’s move the DerivedSingleton class inside the Singleton class. When we move the DerivedSingleton class within the main Singleton class, then it becomes a nested class or you can say a child class of the main singleton class as shown below.

namespace SingletonDemo
{
    public class Singleton
    {
        private static int counter = 0;     
        private static Singleton instance = null;  
        public static Singleton GetInstance
        {
            get
            {
                if (instance == null)
                    instance = new Singleton();
                return instance;
            }
        }  
        private Singleton()
        {
            counter++;
            Console.WriteLine("Counter Value " + counter.ToString());
        }    
        public void PrintDetails(string message)
        {
            Console.WriteLine(message);
        }

        public class DerivedSingleton : Singleton
        {
        }
    }
}
What is a nested class in C#? 

Whenever we defined a class within another class in C# then the inner class is called a nested class or child class. Now if we compile the program then we will not get any error. Let us modify the main method of the program class to access the nested class as shown below.

namespace SingletonDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Singleton fromTeachaer = Singleton.GetInstance;
            fromTeachaer.PrintDetails("From Teacher");
            Singleton fromStudent = Singleton.GetInstance;
            fromStudent.PrintDetails("From Student");
            
            /*
             * Instantiating singleton from a derived class. 
             * This violates singleton pattern principles.
             */
            Singleton.DerivedSingleton derivedObj = new Singleton.DerivedSingleton();
            derivedObj.PrintDetails("From Derived");
            
            Console.ReadLine();
        }
    }
}

Now if you run the application then you will see the following output.

Why Singleton Class Sealed in C#

The above output clearly shows that the counter value has incremented to 2 which proves that the private constructor executed twice and hence it creates multiple instances of the singleton class. So, by removing the sealed keyword we can inherit the singleton class and also possible to create multiple objects of the singleton class. This violates singleton design principles.

Let’s make the Singleton class as sealed as shown below and then compiled the program and see what happens.

namespace SingletonDemo
{
    public sealed class Singleton
    {
        private static int counter = 0;     
        private static Singleton instance = null;  
        public static Singleton GetInstance
        {
            get
            {
                if (instance == null)
                    instance = new Singleton();
                return instance;
            }
        }  
        private Singleton()
        {
            counter++;
            Console.WriteLine("Counter Value " + counter.ToString());
        }    
        public void PrintDetails(string message)
        {
            Console.WriteLine(message);
        }

        public class DerivedSingleton : Singleton
        {
        }
    }
}

Now we got an error when compiling the program saying that we cannot derive a sealed class.

So from this point, we conclude that the private constructor in c# will helps us only preventing any external instantiations of the class and the sealed keyword will prevent the class inheritances.

The above Singleton implementation is not thread-safe. The way we implement the Singleton class, it allows two different threads at the same time to be evaluated the test if (instance == null) and found it to be true and they both create the instances, which violates the singleton design pattern.

In the next article, I am going to discuss how to handle thread safety in singleton class as the current version of singleton implementation can create multiple instances of the singleton class in multi-threaded environments. Here, in this article, I try to explain why the Singleton class sealed in C# step by step with a simple example. I hope this article will help you to understand why the singleton class is sealed in C#.

3 thoughts on “Why Singleton Class sealed in C#”

Leave a Reply

Your email address will not be published. Required fields are marked *