C# Language Constructors and Finalizers Exceptions in static constructors

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

If a static constructor throws an exception, it is never retried. The type is unusable for the lifetime of the AppDomain. Any further usages of the type will raise a TypeInitializationException wrapped around the original exception.

public class Animal
{
    static Animal()
    {
        Console.WriteLine("Static ctor");
        throw new Exception();
    }

    public static void Yawn() {}
}

try
{
    Animal.Yawn();
}
catch (Exception e)
{
    Console.WriteLine(e.ToString());
}

try
{
    Animal.Yawn();
}
catch (Exception e)
{
    Console.WriteLine(e.ToString());
}

This will output:

Static ctor

System.TypeInitializationException: The type initializer for 'Animal' threw an exception. ---> System.Exception: Exception of type 'System.Exception' was thrown.

[...]

System.TypeInitializationException: The type initializer for 'Animal' threw an exception. ---> System.Exception: Exception of type 'System.Exception' was thrown.

where you can see that the actual constructor is only executed once, and the exception is re-used.



Got any C# Language Question?