Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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_;
}
like image 745
Curro Avatar asked Oct 20 '08 13:10

Curro


People also ask

Can we initialize static variable in constructor?

If you declare a static variable in a class, if you haven't initialized it, just like with instance variables compiler initializes these with default values in the default constructor. Yes, you can also initialize these values using the constructor.

Can we initialize static variable in non-static constructor?

Static constructor can initialize only static variable but non-static constructor can initialize both static and non-static variable.

Are static variables initialized before constructor?

All static members are always initialized before any class constructor is being called.

Can we initialize static variable in constructor in C#?

You know that you should initialize static member variables in a type before you create any instances of that type. C# lets you use static initializers and a static constructor for this purpose.


1 Answers

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.

like image 72
Jon Skeet Avatar answered Nov 01 '22 05:11

Jon Skeet