12

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

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Anish
  • 872
  • 5
  • 21
  • 42

4 Answers4

13

If we are giving the constructor as private we can prevent the class to be derived right?

Not quite:

public class NotReallySingleton
{
    private NotReallySingleton() {}

    public class CursesFoiledAgain : NotReallySingleton
    {
    }
}

...

NotReallySingleton x = new CursesFoiledAgain();
NotReallySingleton y = new CursesFoiledAgain();

This works because private access is limited to the program text of the type, including nested types. So CursesFoiledAgain has access to the private constructor of NotReallySingleton.

But even leaving this aside, if your intention is that no-one can derive from the class, why would you not want to signal that intention as clearly as possible, via sealed?

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • @JonSkeet Why would someone derive from your class within your class? This is unusual scenario. If someone can edit your class, they can also add a public parameterized constructor. Inserting a constructor should be easier than inserting a full class. – Deepak Mishra Dec 18 '19 at 09:33
  • @DeepakMishra: There are good reasons to do this in general, e.g. the *good* code in https://codeblog.jonskeet.uk/2014/10/23/violating-the-smart-enum-pattern-in-c/. But more importantly, the question *asserts* that making all constructors private prevents derivation, and the answer refutes that assertion. Whether or not it's a good idea is separate from whether or not the assertion is valid. – Jon Skeet Dec 18 '19 at 09:38
  • @JonSkeet hmm, you are right, the question demands this answer. – Deepak Mishra Dec 18 '19 at 09:47
2

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

These are not the same thing. 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.

Remember that 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.

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
  • You can only derive from the base class *if the derived class has access to the private constructor*. See my answer for the only way in which that's feasible. – Jon Skeet Jul 26 '12 at 11:53
  • However i'm not able to build the following code class BaseClass { private BaseClass() { } } class Derrived : BaseClass { public void Display() { Console.WriteLine("In Derrived class"); } } and i'm getting error like BaseClass.BaseClass()' is inaccessible due to its protection level – Anish Jul 26 '12 at 12:54
0

This is a kind of design guidelines which, obviously, you can follow or not. This is just marking your design intentions like in case of a base class marking it as abstract to avoid possible mess in a future.

sll
  • 61,540
  • 22
  • 104
  • 156
0

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