Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Static field initializers, <em>when you don't have a static constructor</em>, are initialized at an "implementation-dependent" time prior to the first access. This means that they can be initialized at any time - you can't rely on the initialization of <code>Bar.Baz</code> to occur the first time you use <code>Bar</code>.</p> <p>Adding a static constructor to <code>Bar</code> will change the behavior of this to be more of what you're expecting.</p> <p>For details, read the C# language spec, section 10.5.5.1:</p> <blockquote> <p>10.5.5.1 Static field initialization</p> <p>The static field variable initializers of a class correspond to a sequence of assignments that are executed in the textual order in which they appear in the class declaration. If a static constructor (§10.12) exists in the class, execution of the static field initializers occurs immediately prior to executing that static constructor. Otherwise, the static field initializers are executed at an implementation-dependent time prior to the first use of a static field of that class. </p> </blockquote> <p>Also, see 10.2, for details on static constructors:</p> <blockquote> <p>The static constructor for a closed class type executes at most once in a given application domain. The execution of a static constructor is triggered by the first of the following events to occur within an application domain:</p> <p>· An instance of the class type is created.</p> <p>· Any of the static members of the class type are referenced.</p> </blockquote> <p>That being said, if there is deterministic initialization required, I would strongly recommend adding a static constructor to <code>Something</code>, and doing the initialization properly there. In addition to providing a guarantee of the initialization order in this case, it will prevent usage of <code>Something</code> by another class from causing your code to break in the future.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload