26 May 2013

static constructor in C#

In this post let's look at static constructors. Let's try to find the answer to below questions:

  1. What are static constructors and when they get executed
  2. Static constructors usage
  3. Static constructors and .NET AppDomain
  4. Implementing singleton design pattern using static constructor

What are static constructors and their execution:

Below code sample defines a static constructor in C# class.

public class DataManager
{
  // Static constructor in class
  static DataManager()
    {
      // Your logic goes here
    }
}

Static constructors gets executed whenever the class defining the class is loaded into the AppDomain or in other words, static constructors are executed whenever the members of the type accessed for the very first time.

Developer cannot directly invoke static constructors. Static constructors are invoked by Common Language Runtime(CLR) and for this reason, the static constructors are always parameterless. Hence there could always only one static constructor in a class. Using parameters and return type with static constructor will produce compile time error.

a static constructor must be parameter less

member names cannot be the same as their enclosing type

Static constructors doesn't have return type, as they don't return anything.

Access specifiers are not allowed on static constructors. Static constructors are invoked by run time, hence they implicitly public. Using access specifiers with static constructors will result in an error.

access modifiers are not allowed on static constructors.

Static constructors usage:

Static constructors are guaranteed to be thread safe in .NET and they are executed only once. So static constructors are used in place when it is required to do some groundwork before the containing class can be used. Because of this static constructors have found a place in implementing singleton design patterns.

Static constructors and .NET AppDomain

Static constructors are said to be executed during the lifetime of the application. It's not quite correct. In an application, when number of AddDomains are created, for each AppDomain, the static constructor will be invoked once provided you access the class inside the newly created AppDomain.

Implementing singleton design pattern using static constructor

In the below C# code sample, the DataManager class is a singleton class. Using the static constructor, a new instance of DataManager class is created & assigned to private static variable. Using the static method GetInstance() the class instance is returned to the outside world.

public class DataManager
    {
        private static readonly DataManager _instance = null;

        // Static constructor initializes the type
        static DataManager()
        {
            _instance = new DataManager();
        }

        // Static method to get the DataManager singleton object.
        public static DataManager GetInstance()
        {
            return _instance;
        }
        
        // Private constructor in singleton pattern
        // to restrict the object creation to inside the class
        private DataManager(){}
    }
}

As in the above C# code sample, the static constructor can be used to implement singleton design pattern.