This one pertains to CLR.
Please, please, please make sure your static constructors do not throw exceptions. Having static state in a class is already asking for trouble in the case of multiple threads, if that reason wasn’t enough proceed below.
For example,
class A
{
static DataType1 member1 = new DataType1( );
static DataType2 member2 = DataType2.GetDefaultInstance( );
}
If there is even the remotest chance that either DataType1’s constructor or DataType2.GetDefaultInstance will throw an exception you are better off with this version:
class A
{
static DataType1 member1;
static DataType2 member2
static A( )
{
try
{
member1 = new DataType1( );
}
catch( Exception ex )
{
// do some logging
}
try
{
member2 = DataType2.GetDefaultInstance( );
}
catch( Exception ex )
{
// do some logging
}
}
}
The only reason for all this hassle is the avoid throwing uncaught exceptions from .cctor of a type.
Because, for a type whose static constructor throws an exception, EE ensures that no instance of that type will ever be instantiated in that appdomain.
[Update 11/03/09: Many moons after the original post, I come across this. The exact same problem happens in native world.]