O'Reilly logo

C# Cookbook by Jay Hilyard, Stephen Teilhet

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

5.16. Preventing the Nefarious TypeInitializationException

Problem

Problems can occur when initializing a class or a structure’s static fields. Some of these problems are serious enough to raise a TypeInitializationException exception. Unfortunately, this exception can be hard to track down and can potentially shut down your application. You want to prevent this from occurring.

Solution

If you are initializing static fields to a value, null, or not initializing them at all, as is the case with the following class:

public class TestInit
{
    public static object one;
    public static string two = one.ToString( );
}

you should consider rewriting the class to include a static constructor that performs the initialization of the static fields. This will aid in the debugging of your static fields:

public class TestInit
{
    static TestInit( )
               {
               try
               {
               one = null;
               two = one.ToString( );
               }
               catch (Exception e)
               {
               Console.WriteLine("CAUGHT EXCEPTION IN .CCTOR: " + e.ToString( ));
               }
               }

    public static object one;
    public static string two;
}

Discussion

To see this exception in action, run the following method:

public static void Main( )
{
    // Causes TypeInitializationException
    TestInit c = new TestInit( );

    // Replacing this method's code with the following line 
    //    will produce similar results
    //TestInit.one.ToString( );
}

This code creates an instance of the TestInit class. We are assured that any static fields of the class will be initialized before this class is created, and any static constructors on the

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