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?
-
This is discussed in several questions, including [How does static field initialization work in C#? ](stackoverflow.com/questions/710793/…) and [What is the static variable initialization order in C#? ](stackoverflow.com/questions/1405709/…).Matthew Flaschen– Matthew Flaschen2010-10-19 07:09:43 +00:00Commented Oct 19, 2010 at 7:09
-
1@Matthew - good links, but with CLI 4 they may be wrong - or rather: not quite as complete; see hereMarc Gravell– Marc Gravell2010-10-19 07:13:43 +00:00Commented Oct 19, 2010 at 7:13
Add a comment
|
2 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