Feb
Beware of Static Constructors
Filed Under (Bunian, Development) by Emad Alashi on 07-02-2009
Tagged Under : Bunian, code coverage, static constructor
In Bunian we needed to use a static constructor for some reason, it was all going good; we tested the code and it ran smoothly…excellent (Code Coverage anyone?!).
But when I came across this situation, it appeared that the static constructor wasn’t invoked!even when “Class.Method();” is called! so lets examine it.
I have two simple classes as an Example:
public class Parent
{
public static string DoSomething()
{
return “Parent: DoSomething() called”;
}
}
public class Child : Parent
{
static Child()
{
Console.WriteLine(“Child Static constructor called”);
}
public static string DoSomethingDifferent()
{
return “DoSomethingDifferent() called”;
}
}
As it may be obvious, Child inherits from Parent, Child has a static constructor that we need to be executed when ever a method is invoked by Child. Now lets check the main program executing these two lines:
Console.WriteLine(Child.DoSomething()); //This code will NOT invoke the static constructor
Console.WriteLine(Child.DoSomethingDifferent());//This code WILL invoke the static constructor
The surprise (at least to me) when calling “Child.DoSomething()” the static constructor isn’t invoked! because it is in the parent!! aaaaaah! bad!! that was serious for our architecture and we had to do lots of fixes to turns things around the right way (which I think it was for our own good for other reasons
)
This brings up the Code Coverage topic as well; in our case that static constructor’s job was to create an instance of a member that is only needed once, and we check on it in other times by “if _instance != null”. It always ran ok because all the test code we created used to call an original Child before calling any other method that resided in the Parent.
bottom line: be ware of static constructors, and check your test code…it maybe hiding “surprises” for you

