Update: Change in C# 2.0 and Initialising static fields correctly

If you recall the previous post on instantiating static fields, there seems to have been a flurry of activity at Microsoft. As Peter Hallam writes, it made sense to improve the perf. for the static field initialisers and this you should see in Beta2 of Whidbey. The main issue here as Peter explains is if you have a field initialiser for a static field, which initialises the static field to its default value, you still get a static constructor, or .cctor in CLR speak) which is a significant performance penalty. So this begs the question, why did we not add this optimisation for static fields?

There is a subtle difference between instance field initialisers and static field initialisers. When an instance field initialiser begins execution the value of the field being initialised is guaranteed to be the default value. This is a result of 2 things – instance field initialisers run as the first thing after the object is allocated, even before the call to your base class constructor, and during an instance field initialiser, you cannot reference other instance fields of the object being created. This guarantee, that a field’s value is the default before the initialiser is run, does not hold for static fields. This is illustrated by this nasty example:

class C
{
    public C () {}

    // Ugh! assigns y = 5
    private static int x = (C.y = 5);

    // … always does work! changes y from 5 back to 0!!!
    private static int y = 0;
}

More Information: http://blogs.msdn.com/peterhal/archive/2004/10/06.aspx

Published by

Amit Bahree

This blog is my personal blog and while it does reflect my experiences in my professional life, this is just my thoughts. Most of the entries are technical though sometimes they can vary from the wacky to even political – however that is quite rare. Quite often, I have been asked what’s up with the “gibberish” and the funny title of the blog? Some people even going the extra step to say that, this is a virus that infected their system (ahem) well. [:D] It actually is quite simple, and if you have still not figured out then check out this link – whats in a name?

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.