Click here to Skip to main content
Licence CPOL
First Posted 1 Jul 2010
Views 13,320
Bookmarked 16 times

Singletons in C#, Static Constructor vs Static Initialization

By | 1 Jul 2010 | Technical Blog
In C#, you can implement a thread safe singleton where the complexity is hidden in the .NET Framework, you do not even need an if statement!
A Technical Blog article. View original blog here.[^]

Not a long time ago, I posted an article about how to implement a static constructor. As an example, I used a singleton to show how the static constructor works and how it is implemented. The result was a discussion about singletons, what they are good for and how it can be implemented in C#. There is the standard way (how it is normally done) and also a lot easier way for C# with a static constructor or a static initialization.

The Classic Singleton

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

In every object oriented language (or those I know), a Singleton looks nearly (more or less) like the code above. The Singleton restricts the instantiation of a class to one object. This is provided by a static field which holds the instance. If the instance which is stored in the static field is still null, a new object will be created and assigned to the static variable. The code which does the instantiation is locked so it also works in a multi threaded environment (double check locking). Too much code for you? 

Singleton with Static Initialization

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

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

C# allows you to initialize the static field directly (and it also works properly)! The instantiation does occur when instance property is called the first time, so it is some sort of lazy instantiation. .NET takes control that it also works in multi threaded environments, so you have nothing to do with it. But you will still have a problem with that solution if you want to execute custom code before instantiation! With a static constructor, you can solve this problem!

Singleton with Static Constructor

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

   static Singleton()
   {
      instance = new Singleton()
   }

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

It allows you to execute custom code before the singleton is instantiated. But the complexity is still handled by the .NET Framework, so you don't have to implement a double check locking also when you work in multi threaded environments. The static constructor is only executed when the instance property is called the first time. So both variations allow you to implement a thread safe singleton where the complexity is hidden in the .NET Framework. You do not even need an if statement!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Mattia Baldinger

Software Developer

Switzerland Switzerland

Member

Follow on Twitter Follow on Twitter


Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
Generalnice one PinmemberPranay Rana21:41 21 Dec '10  
GeneralCalss per singleton PinmemberAsher Barak1:14 11 Jul '10  
GeneralI'm missing an attribution to John Skeet Pinmemberjeroenp9:59 8 Jul '10  
GeneralMy vote of 4 Pinmemberjohannesnestler3:33 7 Jul '10  
GeneralMy vote of 1 Pinmembermavric21219:17 6 Jul '10  
GeneralJeffrey Richter CLR via C# (second edition) Chapter "The Famous Double-Check Locking Technique" page 642-641 Pinmemberromgun19:37 5 Jul '10  
GeneralMaybe old wine in new sacs PinmemberRozis9:30 2 Jul '10  
GeneralRe: Maybe old wine in new sacs Pinmemberworic14:44 5 Jul '10  
GeneralRe: Maybe old wine in new sacs PinmemberJason Christian20:14 5 Jul '10  
GeneralRe: Maybe old wine in new sacs PinmemberRozis4:57 6 Jul '10  
GeneralRe: Maybe old wine in new sacs [modified] Pinmemberjohannesnestler3:20 7 Jul '10  
GeneralRe: Maybe old wine in new sacs Pinmemberjohannesnestler3:29 7 Jul '10  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web04 | 2.5.120517.1 | Last Updated 2 Jul 2010
Article Copyright 2010 by Mattia Baldinger
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid