Static Constructors: When to Use Them

For the past few years, I’ve gotten quite familiar with static variables. Not only are they useful, but very deadly in multi threading as well. Something I’ve just stumbled upon is the static constructor. In the past, I would instantiate private variables in a static properties’ get method like this:

   private static bool _mInitiated = false;
   public static bool Initiated
{ get { if (_mInitiated = false) _mInitiated = true; return _mInitiated; } set { _mInitiated = value; } }

With a static constructor, we can acquire all of our shared variables and object setup in one sweep, and not cause any application performance issues when accessing properties.

   static SharedClass()
   {
      _mInitiated = true;
   }
   private static bool _mInitiated = false;
   public static bool Initiated
   {
      get {
         return _mInitiated;
      }
      set{
         _mInitiated = value;
      }
   }

The later allows better performance, and sets up the class in a more appropriate place. Some important points regarding static constructors from the C# Language Specification and the C# Programmer’s Reference :

1) The static constructor for a class executes before any instance of the class is created.
2) The static constructor for a class executes before any of the static members for the class are referenced.
3) The static constructor for a class executes after the static field initializers (if any) for the class.
4) The static constructor for a class executes at most one time during a single program instantiation
5) A static constructor does not take access modifiers or have parameters.
6) A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.
7) A static constructor cannot be called directly.
8) The user has no control on when the static constructor is executed in the program.
9) A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.

Hopefully, this would clear the confusion some of developers have about static constructor.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>