Why singleton class should be sealed?

Viewed 7898

I want to know the why a singleton class should be sealed. If we are giving the constructor as private we can prevent the class to be derived right?.. Below i'm pasting few lines from MSDN. Please give me some color on it..

In this strategy, the instance is created the first time any member of the class is referenced. The common language runtime takes care of the variable initialization. The class is marked sealed to prevent derivation, which could add instances. For a discussion of the pros and cons of marking a class sealed, see [Sells03]. In addition, the variable is marked readonly, which means that it can be assigned only during static initialization (which is shown here) or in a class constructor.

http://msdn.microsoft.com/en-us/library/ff650316.aspx

4 Answers

If we are not using sealed keyword for singleton class what is the issue?

Our main goal is we have to create only one object of our singleton class. Please find the below example to understand the concept.

   ///Singleton class
    
        internal class Why_Sealed
        {
          private static int count = 0;
          private static Why_Sealed _instance = null;
          private Why_Sealed()
            {
              count++;
              Console.WriteLine("Count value : " + count);
            }
          public static Why_Sealed Instance
            {
              get{
                  if(_instance == null )
                    {
                     _instnace = new Why_Sealed();
                    }
                    return _instance;
                 }
            }
          private class DerivedClass : Why_Seald
           {
           }
        }
    
    Public class Program
    {
         static void Main()
          {
            var why_Seald_Obj = Why_Seald.Instance;
            var deriveObj = new Derived();
          }
    }

OutPut enter image description here

Related