Click here to Skip to main content
15,896,348 members
Articles / Programming Languages / C#

Static constructor in C#

Rate me:
Please Sign up or sign in to vote.
3.89/5 (6 votes)
25 May 2010CPOL1 min read 48.6K   11   6
When you work with static class variables, the static constructor allows you to create much cleaner code. It gives you the ability to execute code before one of the static methods of the class is executed. You are able to initialize the static variables of your class with no lock or if statement.

Did you ever implement a singleton in C#? For those who don't know what a singleton is, it is a class which can only have one instance, more on Wikipedia. The preferred implementation of a singleton in C# is the following:

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

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

But what would you do if you want to execute some custom code before the instance of the singleton is initialized? You can use the classic singleton code which isn't really different than in other programming languages.

C#
public sealed class ClassicSingleton
{
    private static ClassicSingleton instance;
    private static object syncRoot = new Object();

    private ClassicSingleton() { }

    public static ClassicSingleton Instance
    {
        get
        {
            if (instance == null)
            {
                lock (syncRoot)
                {
                    if (instance == null)
                    {
                        ...custom code
                        instance = new ClassicSingleton();
                    }
                }
            }

            return instance;
        }
    }
}

You have to set the constructor private. A static field of the type of the class holds the single instance. Another static method is the single point of access to get an object of the class. Internally it has to lock the access to the static object to be sure that really only one object will be created. An implementation with a static constructor is easier to handle and also much clearer.

C#
public sealed class Singleton
{
    private static Singleton instance;

    private Singleton() { }

    static Singleton()
    {
        ...custom code
        instance = new Singleton();
    }

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

In this sample, a static constructor is added which initializes the instance of the Singleton class. It will only be called one time, before one of the static methods of the class is called. So the Instance method doesn't have to do this anymore. This results in a much cleaner code, a singleton with no lock or if statement! But also in other cases, when you have static fields in your class, it helps you to avoid the lock and the if statements.

License

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



Comments and Discussions

 
QuestionNIce, short and sweet Pin
Member 451897616-Jun-14 2:54
Member 451897616-Jun-14 2:54 
GeneralExtremely difficult to test Pin
Liam Reilly31-May-10 21:47
Liam Reilly31-May-10 21:47 
GeneralWell done Pin
Khaniya25-May-10 18:22
professionalKhaniya25-May-10 18:22 
I have question there are many article available on codeproject for singleton application.
One of them use following code

private static bool IsAlreadyRunning()
		{
			string strLoc = Assembly.GetExecutingAssembly().Location;
			FileSystemInfo fileInfo = new FileInfo(strLoc);
			string sExeName = fileInfo.Name;
			bool bCreatedNew;

			mutex = new Mutex(true, "Global\\"+sExeName, out bCreatedNew);
			if (bCreatedNew)
				mutex.ReleaseMutex();

			return !bCreatedNew;
		}


so can you explain me which one is better

Thanks for sharing
Life's Like a mirror. Smile at it & it smiles back at you.- P Pilgrim
So Smile Please

GeneralRe: Well done Pin
User 661920726-May-10 19:26
User 661920726-May-10 19:26 
GeneralAlternative Pin
ArchAngel12331-May-10 15:41
ArchAngel12331-May-10 15:41 
GeneralRe: Alternative Pin
User 661920731-May-10 22:24
User 661920731-May-10 22:24 

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

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