Sponsored By

The Actual Singleton Pattern

After stumbling aghast at a blog entry on this site which claimed to describe the singleton OO design pattern and discovering to my horror that it actually had nothing to do with the singleton pattern, I'm going to show you how to do it right. In C#.

Evan Machusak, Blogger

February 28, 2011

8 Min Read
Game Developer logo in a gray background | Game Developer

What is a singleton?

A singleton is a class which by design can only be instantiated exactly 1 time.  It is important to explicitly clarify that because there exists such an entity in C# that can never be instantiated, and those entities are most certainly not singletons.  In order for a class to be called a singleton, it must have one and only one instance.

How to define a singleton in C#:

    class Singleton
    {
        static readonly Singleton Instance = new Singleton();

        protected Singleton()
        {
        }
    }

The primary characteristic of a singleton is that its constructor is not public.  Note that the default access modifier in C# is internal meaning that it is visible to all other classes in the same assembly, so this class is internal.  Internal is considered a public modifier, so you must specify either a protected or private constructor.  However, you must not specify a private constructor unless you also mark the class using the sealed keyword.  C# unfortunately does not enforce this, but creating only private constructors functions the same way as marking the class as sealed as any class you attempt to inherit from Singleton will not compile because the base constuctor is inaccessible.

It is not strictly required that a single, static member (by convention named Instance) be created as a member of the singleton class itself, although in 99% of examples of singletons you see, you'll see a member defined this way.

Singletons must be immutable!

The readonly keyword is absolutely critical here.  Callers must not be able to change the static singleton instance.  If this class were taken in isolation and readonly were omitted, external callers could not reassign the reference to another Singleton instance because another Singleton instance cannot be instantiated (except through reflection), but it could be assigned to null, or any subtype of Singleton, and an external caller would be free to derive his own type because we didn't seal the class with the sealed keyword.  Since we don't want external callers to sabotage our singleton, specifying readonly prevents this field from being assigned after it has been initialized.

If you enable Code Analysis and compile this class, you'll get a warning.  The warning will alert you that Singleton must itself be a read-only class for this static member to actually be read-only.  What does that mean?

Suppose we elaborate Singleton to include members, like this:

    class Singleton
    {
        static readonly Singleton Instance = new Singleton();

        private Singleton()
        {
        }

        public string Name { get; set; }
    }

If your class were designed this way, Code Analysis would be alerting you to a serious design flaw in your singleton - namely, that your global, single, unique instance is mutable.  It has a state.  That state can be changed.  This is terrible design.  Your singleton now functions as a global variable and global variables are bad.  Global members are not.  Singletons are not global variables, because they are not variable.

As a general rule, if a class has some kind of state and that state can be changed after creation time then your class is automatically not eligible to be made a singleton. 

Code Analysis cannot (or, rather, does not) attempt to detect whether the type to which the readonly attribute is applied is actually mutable or not, so it issues a warning regardless and tells you to suppress the warning if you, the designer, knows definitively that your class is immutable.  Since we know this, we would suppress the warning.

You may think that a property is a way around a Code Analysis warning, but if you use a property, you'll end up issuing a different one.  Example:

    class Singleton
    {
        public static Singleton Instance { get; private set; }

        private Singleton()
        {
        }      

    }

Useless in this incarnation because you will note that we haven't set the value of the property yet.  And since you cannot inline the initialization of a property declared this way as you can with a field, you're stuck.

If you're an amateur you might think the solution is lazy initialization and do something silly like this:

 class Singleton
    {
        public static Singleton Instance
        {
            get
            {
                if (_instance == null)
                    _instance = new Singleton();
                return _instance;
            }           
        }
        private static Singleton _instance;

        private Singleton()
        {
        }

    }

Also an absolutely terrible idea - you're now inlining a runtime null check every time your singleton is used in order to solve a compile time code design issue.  If I ever see anyone on my team do something like this, I pull him into my office and explain that last sentence to him in much more lurid detail.  Do not solve design-time problems with run-time checks.

If you have to use lazy initialization, use the Lazy class.  It's new in .NET 4.

But in the static context it's another code analysis violation to leave any static member uninitialized.  Static members should virtually always be intialized inline.  There are some exceptions to that rule that are unavoidable (e.g., the class requires more than one line to initialize it and set its state), but that should occur very rarely.

Another alternative is to use the static constructor (also known as a type initializer), but you shouldn't use type initializers if you can avoid it - it's a performance issue that is beyond the scope of this article.  That would look like this:

    class Singleton
    {
        public static Singleton Instance { get; private set; }

        static Singleton()
        {
            Instance = new Singleton();
        }

        private Singleton()
        {
        }
    }

Don't do this.  The best way is to declare a public readonly static field and suppress the Code Analysis after you, the human programmer, has confirmed that your readonly field is of an immutable type.

When should I use singletons?

Singletons should be used any time a class has no state, meaning it has no properties or fields that will ever change throughout the course of execution.  The most common scenario for singletons is when you are overriding a class or implementing an interface which defines only methods.  If an interface defines only methods, then 99% of the time, implementations of that interface should be singletons.

In effect, singletons are stateless objects, however...

Singletons are not your first choice for stateless objects.

Just as there exist static members in classes, when a class defines only static or const members, the class itself should be marked static.  An example of a static class that you may happen upon in game development if you use XNA would be the MathHelper class, which defines only static computation methods and constant values.  There is no such thing as a const class.

Static classes cannot be instantiated and therefore they are not and can never be considered singletons.  But static classes are more efficient than instanced classes in every case, so if it is possible to mark a class static, you should.  Generally speaking, you should already know that the class should be static before you start defining it, as the guys who wrote MathHelper did.  Static classes should be thought of as method libraries or a scope for defining related constant values, not as true objects.

Static classes cannot be inherited and therefore if you intend on creating an interface or a base class that defines functionality that you intend to be inherited, you must not mark your class static and instead you should implement the base as a singleton, if applicable.  Making a base class a singleton is a good cue to your inheritors that they should probably be designing singletons, too, and thus should avoid state properties or fields.

Singletons should mostly appear when...

... you are designing an interface or base class that contains only methods, or you are inheriting from such a class or implementing such an interface.

For example:

    interface IGameSaveWriter
    {
        void Write(SavedGame game);
    }
    class GameSaveDiskWriter : IGameSaveWriter
    {
        public static readonly Singleton Instance = new GameSaveDiskWriter();
        private GameSaveDiskWriter()
        {
        }

        public void Write(SavedGame game)
        {
            // write to disk
        }
    }

Of course, a class that saves a game file to disk would most likely take some kind of state like a base directory to store the save files, but for the sake of argument let's assume that location is fixed or comes from the registry.

That's the singleton pattern.  Learn it, love it, and use it responsibly.

Remember, the entire point of design patterns is to use the rules of object-oriented design to force the consumers of your code to use it in the way you intended.  In the case of the singleton pattern, you apply it to prevent consumers from mistakenly assuming the class has some kind of state and that they must instantiate an instance to use it.  If you use the singleton pattern in any other way, you're abusing it and wasting everyone's time.

Even if you're the only consumer of your own classes, you should still apply design patterns where they fit to protect you from yourself.  It's very easy to make a lot of programming mistakes.  OO design patterns help reduce mistakes, whether it's you making them or a co-worker or a public consumer who downloaded your samples from CodePlex. 

Read more about:

Blogs
Daily news, dev blogs, and stories from Game Developer straight to your inbox

You May Also Like