Static Constructors

Summer Ball Star

One of the few nice things about marking all the programming exam papers over the last week was the number of people who seemed to understand what “static” means in a programming context. While one or two did make the mistake of putting ‘static means that you can’t change it’ and getting both a muffled oath and zero marks from me most answered “static means that it always there, like the continuous background hiss from a badly tuned FM radio”. Actually, not all of them were as poetic as that, but they all knew that the thing about static items is that you don’t have to make them, your program can use them without having to create any instances.

Pressed for uses of static their answers made sense too, constants that you want everyone in a class to make use of, validation values and methods, all the sensible stuff. I didn’t ask about static constructors though, which is the next step along the road.

If you want to set up an instance of a class you add a constructor method that runs when an object of that type is created. These can be given values so that you can pre-set your object with data at the beginning of its life. Bank accounts can be given account holder names and starting balance values, sprites can be given textures and positions.

Sometimes you might want to perform some code to set up values in your static class. For example a class providing some constants for your program might need to read some system settings first. Unfortunately you can’t use a normal constructor for this because (duh!) we never make an instance of a static class. Instead though you can use a static constructor. This is just like a normal constructor, but has the keyword static in front:

public static class Settings
   public static int Number;
   static Settings ()
        // code in here is performed when
        // the class is loaded
        Number = 99;

The thing to remember about this is that the static constructor is run when the class is loaded, not at the start of the program. The first time your program reaches a statement like:

int i = Settings.Number;

- that is when the Settings class is loaded and the static constructor runs. In order to reduce memory use and time spent processing unwanted code the .NET runtime system only loads classes when they are needed, so if we never use a value from the Settings class it is never brought into memory and the static constructor never runs. Don’t think of static constructors all running when your program starts, they only run when the classes that contain them are loaded.

In fact any class can contain a static constructor that runs when it is loaded, not just static ones. If you need to get something set up before anybody uses your object just use the construction above to get control when the class is brought in. One way to find out if a particular class is ever actually used in your program is to add a static constructor and then put a breakpoint in it.