Simple Singleton Based on Jon Skeet Singleton

I need a singleton in my code. I read the Jon Skeet page in singleton and selected this model (# 4) according to his recommendation:

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;
        }
    }
}

Then I took a few steps to change this to fit my scenario:

Step 1: I do not need a lazy implementation, so I pulled out a static constructor (as John suggested at the end of his article):

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

    private Singleton(){}

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

Step 2: Then I changed the class “instance” to the Singletonclass LoggingI am working with:

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

    private Singleton(){}

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

Step 3: Then Resharper told me that I should use the auto property for my "Instance" property:

public sealed class Singleton
{
    private Singleton(){}

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

Step 4: Then Resharper told me that I should switch it to a static class:

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

, , . , Singleton .

, : . - Singleton?

+4
1

- , Singleton?

, .

, 1, . ; init, Lazy<T> , .

2 , (Logging).

, " Singleton".

+3

Source: https://habr.com/ru/post/1669868/


All Articles