O'Reilly logo

C# 5.0 Unleashed by Bart De Smet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

TypeInitializationException

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; } } ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required