Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the singleton implementation in C# 6.0 does not need the beforefieldinit flag?

Tags:

c#

singleton

I'm trying to understand why this is a correct implementation of the Singleton pattern:

public sealed class Singleton : ISingleton
{
    public static Singleton Instance { get; } = new Singleton();

    private Singleton() { }

    // methods
}

What about the beforefieldinit flag? According to Jon Skeet article:

The laziness of type initializers is only guaranteed by .NET when the type isn't marked with a special flag called beforefieldinit. Unfortunately, the C# compiler (as provided in the .NET 1.1 runtime, at least) marks all types which don't have a static constructor (i.e. a block which looks like a constructor but is marked static) as beforefieldinit.

Is the static constructor not needed in the newest version of C#?

The code above is the implementation of SystemClock in NodaTime project, by Jon Skeet.'

EDIT Jon Skeet code for reference (why I'm mentioning this beforefieldinit flag):

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

    // Explicit static constructor to tell C# compiler
    // not to mark type as beforefieldinit
    static Singleton()
    {
    }

    private Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            return instance;
        }
    }
}
like image 781
Patryk Golebiowski Avatar asked Mar 21 '16 14:03

Patryk Golebiowski


People also ask

Why we are using singleton?

Singleton pattern restricts the instantiation of a class and ensures that only one instance of the class exists in the java virtual machine. The singleton class must provide a global access point to get the instance of the class. Singleton pattern is used for logging, drivers objects, caching and thread pool.

Why singleton is used in C#?

One of the commonly used design patterns in C# is the singleton pattern. This design pattern uses a single instance of a class to enable global access to the class members. Instead of having several instances of the same class, singletons have just one instance, and provide convenient access to that single instance.


1 Answers

Both are correct singleton implementations. Whether you need the static constructor just depends on how much you care about full laziness. If you really, really don't want the singleton to be instantiated until it's used by a caller, you should have a static constructor - or use Lazy<T>. You can use a static constructor in the C# 6 code as well, of course:

public sealed class Singleton : ISingleton
{
    public static Singleton Instance { get; } = new Singleton();

    static Singleton() { }
    private Singleton() { }

    // methods
}
like image 135
Jon Skeet Avatar answered Oct 22 '22 06:10

Jon Skeet