sealed keyword means that the class cannot be inherited. Declaring the constructor as private means that no instance of the class can 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 the base class.
Constructors is not inherited (so the derived class won't just because the base class has all private constructors), and the derived class always calls the base class constructor first.
Marking a class as sealed prevents someone from working around your carefully constructed singleton class because it prevents someone from inheriting from the class.
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 { } }
The above is the detailed content of Why are singleton classes in C# always sealed?. For more information, please follow other related articles on the PHP Chinese website!