Throwing an exception from a static constructor is not considered good practice because the exception can surface in totally unexpected places where the CLR decides to run the static constructor. Keep in mind that static field initialization code ends up in the static constructor as well, providing another potential source of exceptions.

The problem of a static constructor throwing an exception is illustrated in the following example, and Figure 23.15 shows the result of running the code:

class Program {    static void Main(){        Console.WriteLine(StaticBoom.X);    }}static class StaticBoom {    static int x = 0;    static int y = 1 / x;    public static int X { get { return x; } }}

Figure 23.15. A static constructor ...

Get C# 4.0 Unleashed now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.