Diasparsoft Logo Let's write software that people understand.

Home | Contact

Training

JUnit support

Outsourcing

The work that Diasparsoft did for us was outstanding. We are now using the software on a daily basis and their work could well have a dramatic impact on the Reds' organization in the near future.Cincinnati Reds Baseball Club.


Publications

Tips & Tricks

Diasparsoft Toolkit

What is Diaspar?

Interesting Bits RSS

Home » Archives » June 2004 » C# for Java Programmers: Static Constructors

[Previous entry: "Introducing "C# for Java programmers""] [Next entry: "Building Bugs in Double-Quick Time, part 1"]

06/30/2004: "C# for Java Programmers: Static Constructors"


The C# static constructor is similar to the Java static initializer, with one major difference: in C#, there is no guarantee that the static constructor will execute.

According to Jesse Liberty's Programming C#:

You are not able to control exactly when a static constructor will run, but you do know that it will be after the start of your program and before the first instance is created. Because of this you cannot assume (or determine) whether an instance is being created.

Although I find the last bit of this explanation a little wonky, it appears that the static constructor may not execute if no instance of the corresponding class is ever created. In Java, the static initializer does execute when the class loads.

The Point: C#'s static constructor can be used for automatic lazy initialization of class-level data without worrying that the initialization effort will be "wasted" by never using the data.