Difference initializing static variable inline or in static constructor in C#

12,204

Solution 1

If you have a static constructor in your type, it alters type initialization due to the beforefieldinit flag no longer being applied.

It also affects initialization order - variable initializers are all executed before the static constructor.

That's about it as far as I know though.

Solution 2

In this case I don't believe there si any practical difference. If you need some logic in initializing the static variables - like if you would want to use different concrete types of an interface given different conditions - you would use the static constructor. Else, the inline initialization is fine in my book.

class Foo
{
    private static IBar _bar;

    static Foo()
    {
        if(something)
        {
            _bar = new BarA();
        }
        else
        {
            _bar = new BarB();
        }
    }
}
Share:
12,204
Curro
Author by

Curro

I've been programming for 20+ years in many different languages, and I hope to keep writing programs in many other languages to come. Currently, I do most of my work in C# and Managed C++, and I use Python for most of my personal projects or small automation scripts. Othere interests include, digital photography, music (I play piano and guitar), and magic.

Updated on June 25, 2022

Comments

  • Curro
    Curro almost 2 years

    I would like to know what is the difference between initializing a static member inline as in:

    class Foo
    {
        private static Bar bar_ = new Bar();
    }
    

    or initializing it inside the static constructor as in:

    class Foo
    {
        static Foo()
        {
            bar_ = new Bar();
        }
        private static Bar bar_;
    }