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_;
}
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.
Static constructor can initialize only static variable but non-static constructor can initialize both static and non-static variable.
All static members are always initialized before any class constructor is being called.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With