Thursday, August 9, 2018

Why singleton should be sealed?

public class NotReallySingleton
{
    private NotReallySingleton() {}

    public class CursesFoiledAgain : NotReallySingleton
    {
    }
}

...
 NotReallySingleton x = new NotReallySingleton.CursesFoiledAgain();
 NotReallySingleton y = new NotReallySingleton.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?

No comments:

Followers

Link