FAQ
overflow

Great Answers to
Questions About Everything

QUESTION

Is this the best way to implement this pattern in C#?

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

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

{ asked by Aim Kai }

ANSWER

I use Jon Skeet's version of a thread safe Singleton with fully lazy instantiation in C#:

public sealed class Singleton
{
    // Thread safe Singleton with fully lazy instantiation รก la Jon Skeet:
    // http://csharpindepth.com/Articles/General/Singleton.aspx
    Singleton()
    {
    }

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

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

        internal static readonly Singleton instance = new Singleton();
    }
}

It works wonders for me! It's really easy to use, just get the instance from the Instance property like so; SingletonName instance = SingletonName.Instance;

{ answered by Zolomon }
Tweet