Arbejdsglæde
Arbejdsglæde

Reputation: 14088

Singleton in C#

I would like to collect more variants for create singleton class. Could you please provide to me the best creation way in C# by your opinion.

Thanks.

public sealed class Singleton
{
    Singleton _instance = null;

    public Singleton Instance
    {
        get
        {
            if(_instance == null)
                _instance = new Singleton();

            return _instance;
        }
    }

    // Default private constructor so only we can instanctiate
    private Singleton() { }

    // Default private static constructor
    private static Singleton() { }
}

Upvotes: 1

Views: 672

Answers (2)

alexl
alexl

Reputation: 6851

look here : http://www.yoda.arachsys.com/csharp/singleton.html

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

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

    Singleton()
    {
    }

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

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1499770

I have an entire article on this which you may find useful.

Oh, and try to avoid using the singleton pattern in general, due to its pain for testability etc :)

Upvotes: 12

Related Questions