
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Preventing the Nefarious TypeInitializationException
|
417
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. You are assured that any static
fields of the class will be initialized before this class is created, and any static con-
structors on the
TestInit class will be called as well. The TestInit class is written as
follows:
public class TestInit
{
public static object one = null;
public static string two = one.ToString( );
}
As you can see, a NullReferenceException should be thrown on the second static
field, since it is trying to call
ToString on an object set to null. If run from the devel-
opment ...