.net – Why singleton class should be sealed

class-designdesign-patternsnetsealedsingleton

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

Best Answer

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?