Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When do static variables get initialized in C#?

Tags:

c#

static

I was wondering about when does a static variable(in a class) come into picture(initialized)? Is it after the instance constructor called for the first time or after the class loads? When does a class loading occur?

like image 363
badmaash Avatar asked Oct 19 '10 06:10

badmaash


People also ask

How are static variables initialized in C?

In C, static variables can only be initialized using constant literals. For example, following program fails in compilation. If we change the program to following, then it works without any error.

How static variables are initialized?

A static variable in a block is initialized only one time, prior to program execution, whereas an auto variable that has an initializer is initialized every time it comes into existence. A static object of class type will use the default constructor if you do not initialize it.

Are static variables always initialized to zero in C?

3) Static variables (like global variables) are initialized as 0 if not initialized explicitly.

Are static variables initialized before main?

Global (namespace) variables or static class members 1 live for the entire execution of the program: they must be initialized before main() is run and destroyed after execution finishes.


1 Answers

Oh, that is complex. It depends on whether the beforefieldinit flag is set, which in turn (in C#) depends on whether there is a static constructor. And worse; in .NET 4 I believe the behaviour changed to make it more "lazy" than it used to be.

Frankly, I wouldn't code to any specific behaviour here; simply: static fields will be initialized before you try to use them, as long as you use regular code to access them.

Jon Skeet has a good write-up on this here and here

like image 69
Marc Gravell Avatar answered Sep 20 '22 15:09

Marc Gravell