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

Get C# Cookbook 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.