The product of a web developer with a little too much caffeine

Static Constructors — What? What???

with 3 comments

The best days of the year fall on the days that I learn something so completely new and useful in C# that I literally rush out to find a good place to use it. It has happened several times over the years, for example when discovered coalescing operators and ternary operators (not limited to C# but you get it).

Well, that great day has arrived again!

So look at this code – I write code like this fairly often…

/// <summary>
/// Manages resources or something...
/// </summary>
public class WebResources {

    /// <summary>
    /// Returns a list of resource files
    /// </summary>
    public static IEnumerable<Resource> ResourceList {
        get {

            //check for the resource
            if (WebResources._ResourceList == null) {
                WebResources._ResourceList = WebResources._LoadResources();

            //return the resources
            return WebResources._ResourceList;

    private static IEnumerable<Resource> _ResourceList;


The goal of the code was to create a static property that only allowed for you to get the values. I’d always end up having to write extra code to check for the value then load it if it wasn’t ready yet. This threw an extra if statement into every request.

While a single extra comparison isn’t really going to be a big deal I still felt the code hurt the clarity of the class. Properties are rarely supposed to do anything. Talking to external resources and loading files… not really a good idea. Not only that, it placed setup code in the middle of the class instead up mixed in with the constructors where it really belongs.

However, behold coding greatness…

/// <summary>
/// Manages resources or something...
/// </summary>
public class WebResources {

    //Oh yeah!!
    static WebResources() {
        WebResources.ResourceList = WebResources._LoadResources();

    /// <summary>
    /// Returns a list of resource files
    /// </summary>
    public static IEnumerable<string> ResourceList { get; private set; }


You see that? A static constructor! It feels like I’ve discovered something rare like a unicorn or something… but in the form of a code snippet.

Now you should note that this code doesn’t run as soon as your application starts. Instead, it is fired off the first time you access the class. It is important to keep that in mind – Imagine if you have a long running process and it kicks off in the middle of your programming running. Here are a few examples of what I mean…

Examples where the static constructor will NOT run

//checking the type against another object
someObject is WebResources

//loading the Type data for the class

//trying to cast the value
WebResources temp = someObject as WebResources;

Examples where the static constructor WILL run

//creating an instance
WebResources resources = new WebResources();

//accessing a property
IEnumerable<Resource> resources = WebResources.Resources;

//using an inheriting class
public class SuperWebResources : WebResources { }
IEnumerable<Resource> resources = SuperWebResources.Resources;

Its too bad I’m only just now finding out about this little gem of code. I’m sure some of you smart devs could have clued me in about this a long time ago. I guess that’s just the way it goes being the only programmer in your company for this long… Oh well… 😐

Anyways – Helpful? Known it all along (And if so, why have you been holding out on me!)


Written by hugoware

March 28, 2010 at 9:18 pm

Posted in General Discussions

Tagged with , , ,

3 Responses

Subscribe to comments with RSS.

  1. Good stuff, lots of use cases, very efficient way to load resources before static method execution, sweet!

    Ricardo Rodrigues

    March 29, 2010 at 3:48 am

  2. There is one problem with this approach.
    Assume you have more than one static property in your class which needs lazy initialization. In that case, accessing one of the properties will trigger loading all the other irrelevant properties, and synchronously!
    My personal favorite pattern is using a method like EnsureResourceList() in the get accessor, which will contain the if, acquire any necessary synchronization locks and do the initialization.

    Yitzhak Steinmetz

    March 31, 2010 at 3:40 pm

    • If you have a lot of static properties that have long running initialization processes then you might see a performance hit – but you’re going to incur it sooner to later. In that scenario you might favor explicitly calling a ‘init’ method of sorts at the application start and get it out of the way.

      I agree with you that a static constructor removes your ability to selectively choose which properties are initialized but you also gain additional clarity in your code. Every situation is going to be different so you’ll need to decide when you get there.

      My opinion has been that a property shouldn’t ‘do’ anything but instead simply return information. Initialization logic in a property, especially something that might cause an exception, might cause some confusion with a programmer.

      Thanks for the comment!


      March 31, 2010 at 4:09 pm

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: