Singleton Pattern for C# [closed]

Typically a singleton isn’t a static class – a singleton will give you a single instance of a class.

I don’t know what examples you’ve seen, but usually the singleton pattern can be really simple in C#:

public sealed class Singleton
{
    private static readonly Singleton instance = new Singleton();
    static Singleton() {} // Make sure it's truly lazy
    private Singleton() {} // Prevent instantiation outside

    public static Singleton Instance { get { return instance; } }
}

That’s not difficult.

The advantage of a singleton over static members is that the class can implement interfaces etc. Sometimes that’s useful – but other times, static members would indeed do just as well. Additionally, it’s usually easier to move from a singleton to a non-singleton later, e.g. passing in the singleton as a “configuration” object to dependency classes, rather than those dependency classes making direct static calls.

Personally I’d try to avoid using singletons where possible – they make testing harder, apart from anything else. They can occasionally be useful though.

Leave a Comment