Search code examples
c#singletonautomatic-properties

Is implementing a singleton using an auto-property a good idea?


I recently found out about auto-properties and like them quite a lot. At this moment I am trying to use them everywhere where I can. Not really to just be able to use them everywhere, but more to see how well they work in most situations.

Now I am making a singleton and thought:"Hey, let's try auto-properties here as well".

public class MySingleton
{
    public static MySingleton MySingleton { get; private set; }

    private MySingleton() {}

    static MySingleton() { MySingleton = new MySingleton(); }
}

So my question is: "Is it a good idea to implement a singleton like this?"

I am not asking whether a singleton in general is a good idea.


Solution

  • I wouldn't personally do that. I don't like using automatically implemented properties with a private setter that you never call where really you want a read-only property backed by a read-only variable. It's only one more line of code to be more explicit about what you mean:

    public sealed class MySingleton
    {
        private static readonly MySingleton mySingleton;
        public static MySingleton MySingleton { get { return mySingleton; } }
    
        private MySingleton() {}
    
        static MySingleton() { mySingleton = new MySingleton(); }
    }
    

    This way no-one's even tempted to change the singleton class to reassign either the property or the variable, because the compiler will stop them. They'd have to add a setter and/or make the variable non-readonly, which is a bigger change - one which hopefully they'd reconsider.

    In other words:

    • Yes, it will work.
    • No, I don't think it's a good idea.

    As of C# 6, this is easier with read-only automatically implemented properties though:

    public sealed class MySingleton
    {
        public static MySingleton MySingleton { get; } = new MySingleton();    
        private MySingleton() {}         
        static MySingleton() {}
    }