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?
Asked
Active
Viewed 1.9k times
34
-
This is discussed in several questions, including [How does static field initialization work in C#? ](http://stackoverflow.com/questions/710793/how-does-static-field-initialization-work-in-c) and [What is the static variable initialization order in C#? ](http://stackoverflow.com/questions/1405709/what-is-the-static-variable-initialization-order-in-c). – Matthew Flaschen Oct 19 '10 at 07:09
-
1@Matthew - good links, but with CLI 4 they may be wrong - or rather: not *quite* as complete; [see here](http://msmvps.com/blogs/jon_skeet/archive/2010/01/26/type-initialization-changes-in-net-4-0.aspx) – Marc Gravell Oct 19 '10 at 07:13
2 Answers
40
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

ana
- 1,071
- 9
- 12

Marc Gravell
- 1,026,079
- 266
- 2,566
- 2,900
1
Static variables comes into picture after the corresponding class loading. It is not after constructor calling, because constructor calling comes into play when we are using new operator to create object of class and static variables are available on class level not on object level.

traveller
- 39
- 1
- 7