views:

1145

answers:

1
public sealed class Singleton
{
    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();
    }
}

I wish to implement Jon Skeet's Singleton pattern in my current application in C#.

I have two doubts on the code

1) How is it possible to access the outer class inside nested class?

I mean internal static readonly Singleton instance = new Singleton(); Is something called closure?

2) I did not get this comment

// Explicit static constructor to tell C# compiler
            // not to mark type as beforefieldinit

what does this comment suggest us?

+10  A: 
  1. No, this is nothing to do with closures. A nested class has access to its outer class's private members, including the private constructor here.

  2. Read my article on beforefieldinit. You may or may not want the no-op static constructor - it depends on what laziness guarantees you need. You should be aware that .NET 4 changes the actual type initialization semantics somewhat (still within the spec, but lazier than before).

Do you really need this pattern though? Are you sure you can't get away with:

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

     static Singleton() {}
     private Singleton() {}
 }
Jon Skeet
+1 I'm trying to compete with Jon Skeet on a clarification about Jon Skeet's pattern, this isn't going to go well...
LorenVS
hmm... am I wrong or does your new example never actually create an instance of Singleton???
LorenVS
@LorenVS: Oops. That's the problem with rushing the code while trying to get off a train :)
Jon Skeet
You is on a train AND coding... Major jealousy
LorenVS