Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Singleton pattern - a simplified implementation?

The singleton pattern implementation suggested in C# in Depth is

public sealed class Singleton
{
    private static readonly Singleton instance = new Singleton();
    static Singleton()
    {
    }

    private Singleton()
    {
    }

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

ReSharper suggests to simplify this using an auto property and the C# 6 auto-property initializer:

public sealed class Singleton
{
    static Singleton()
    {
    }

    private Singleton()
    {
    }

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

This does indeed look simpler. Is there a down-side to using this simplification?

like image 484
Petter T Avatar asked Aug 17 '17 07:08

Petter T


1 Answers

On site https://sharplab.io you can look at IL code, in both cases IL code are similar. So this should work same way.

like image 99
BWA Avatar answered Nov 15 '22 08:11

BWA