views:

111

answers:

4

I was reading up on singleton class design in C# on this great resource and decided to go with alternative 4:

public sealed class Singleton1
{
    static readonly Singleton1 _instance = new Singleton1();

    static Singleton1()
    {
    }

    Singleton1()
    {
    }

    public static Singleton1 Instance
    {
        get
        {
            return _instance;
        }
    }
}

Now I wonder if this can be rewritten using auto properties like this?

public sealed class Singleton2
{
    static Singleton2()
    {
        Instance = new Singleton2();
    }

    Singleton2()
    {
    }

    public static Singleton2 Instance { get; private set; }
}

If its only a matter of readability I definitely prefer the second version, but I want to get it right.

+4  A: 

This is not equivalent, as the backing field of the autoproperty will not be readonly.

Oded
+7  A: 

It would work correctly, but it is not really the same.

Even if the property is marked as private, it is not read-only (e.g. assignable in the constructor only). Therefore you should use the first variant, which expresses the intent of having a variable (reference) which does not change after its initial assignment.

Lucero
A: 

The backing field of the property is not readonly but as this is a private property it is not that great an issue. But the big advantage for the first implementation is that you can drop the static constructor, but for the second one you use a static constructor. A static constructor can add a performance hit (see http://msdn.microsoft.com/en-us/library/ms182275(v=VS.100).aspx )

Cornelius
The performance hit comes from the class being marked as "beforefieldinit", which is needed for thread safety. The article on singletons mentions this.
Cameron MacFarland
A: 

Another thing to consider here is that initializing a property is more work than just initializing a field.

The static constructor in Singleton2 calls the set method on the property, which then sets the value of the backing field. I have no idea if or how this affects thread safety but it's another difference.

Cameron MacFarland