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
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
?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With