Static Initializers vs. Static Constructors

Static types generally have static member variables that need to be initialized before an instance of the type can be used. There are a couple of common ways to do that. A static constructor can initialize those variables before they are accessed. They are a good option when you need to have logic built into the initialization process. Static initializers are useful when you only have to allocate the static member.

        private static readonly WeatherMan _instance = new WeatherMan();
        static WeatherMan()
        {
            _instance = new WeatherMan();
        }

If there is a reasonable chance that initializing a member variable could result in an exception, you may want to consider using a static constructor. You can’t catch an exception from a static initializer, with a static constructor you can. If an exception occurs in a static constructor, your program will terminate with an exception. If the caller of the static constructor tries to catch the exception, future attempts to create an instance of the type will fail until the AppDomain is unloaded. Ouch. So the only real option is to catch the exception in the static constructor, and add some recovery logic.

Leave a Reply

Your email address will not be published. Required fields are marked *