7

As you can see from my nickname I'm newbie actually learning about Singleton pattern, where I got one problem. Before I've learned that static constructors are always executed before the standard constructors, but in this code below, the result is different, first I see the "Insta" string then the "Static", why does it happen ?

sealed class Singleton
{
    private static readonly Singleton instance;

    private Singleton()
    {
        Console.WriteLine("Insta");
    }

    static Singleton()
    {
        instance  = new Singleton();
        Console.WriteLine("Static");
    }

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

class Program
{
    static void Main()
    {
        Singleton s1 = Singleton.Instance;

    }

}
2
  • 2
    Related: csharpindepth.com/Articles/General/Singleton.aspx Commented Jul 3, 2013 at 20:46
  • 1
    Not sure on reasoning of your expectation - "static constructor called first" does not mean "all code in static constructor magically executed before all calls to class members" (instance constructor in your case). Commented Jul 3, 2013 at 20:50

3 Answers 3

13

If you will write

static Singleton()
{
    Console.WriteLine("Static"); //THIS COMES FIRST
    instance  = new Singleton();

}

you would see what you expect

static ctor is executed at first, as expected, but you print on console after the instance = new Singleton(); line, but this line execute instance ctor, so "inst".

So execution flow:

  • static ctor
    • instance = new Singleton();
      • instance ctor prints "insta"
    • "static"
Sign up to request clarification or add additional context in comments.

4 Comments

Right my fault, thanks. But I have one more ask for you what if i write "private static readonly Singleton instance = new Singleton();" Will compiler move this expression to static ctor or what?
@CSharpBeginner no, the Singleton instance will be constructed the first time the class is called, you would no longer need a static constructor
So this initializtion works the same way static ctor does right ?
@CSharpBeginner: if saying "same way", you mean initialized only once, yes.
9

See the MSDN pattern here for a quality explanation of the singleton pattern.

MSDN recommends you should write it as below so it is thread safe:

using System;

public sealed class Singleton
{
   private static volatile Singleton instance;
   private static object syncRoot = new Object();

   private Singleton() {}

   public static Singleton Instance
   {
      get 
      {
         if (instance == null) 
         {
            lock (syncRoot) 
            {
               if (instance == null) 
                  instance = new Singleton();
            }
         }

         return instance;
      }
   }
}
 

By the way, this pattern has the following advantage over static constructor:

The instantiation is not performed until an object asks for an instance; this approach is referred to as lazy instantiation. Lazy instantiation avoids instantiating unnecessary singletons when the application starts.

See if this feets your need, and if so, implement this solution.

2 Comments

What does thread safety have to do with a conceptual question like this one?
My point is to present the MSDN article in how to implement a singleton solution. No need to reinvent the wheel. Since he is a beginner it is always good to have a good solid article to read and understand a specific pattern.
1

The static method is invoked first. Here's the proof--change your code to the following:

static Singleton()
    {
        Console.WriteLine("Static method start");
        instance  = new Singleton();
        Console.WriteLine("Static method end");
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.