Why singleton class is always sealed in C#?

CsharpServer Side ProgrammingProgramming

The sealed keyword means that the class cannot be inherited from. Declaring constructors private means that instances of the class cannot be created.

You can have a base class with a private constructor, but still inherit from that base class, define some public constructors, and effectively instantiate that base class.

Constructors are not inherited (so the derived class won't have all private constructors just because the base class does), and that derived classes always call the base class constructors first.

Marking the class sealed prevents someone from trivially working around your carefully-constructed singleton class because it keeps someone from inheriting from the class.

Example

static class Program {
   static void Main(string[] args){
      Singleton fromStudent = Singleton.GetInstance;
      fromStudent.PrintDetails("From Student");

      Singleton fromEmployee = Singleton.GetInstance;
      fromEmployee.PrintDetails("From Employee");

      Console.WriteLine("-------------------------------------");

      Singleton.DerivedSingleton derivedObj = new Singleton.DerivedSingleton();
      derivedObj.PrintDetails("From Derived");
      Console.ReadLine();
   }
}
public class Singleton {
   private static int counter = 0;
   private static object obj = new object();

   private Singleton() {
      counter++;
      Console.WriteLine("Counter Value " + counter.ToString());
   }
   private static Singleton instance = null;

   public static Singleton GetInstance{
      get {
         if (instance == null)
            instance = new Singleton();
         return instance;
      }
   }

   public void PrintDetails(string message){
      Console.WriteLine(message);
   }

   public class DerivedSingleton : Singleton {
   }
}
raja
Published on 25-Nov-2020 12:08:03
Advertisements