[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.
