Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>See <a href="http://csharpindepth.com/Articles/General/Beforefieldinit.aspx" rel="nofollow noreferrer">my article</a> on this very issue.</p> <p>Basically, <code>beforefieldinit</code> means "the type can be initialized at any point before any static fields are referenced." <em>In theory</em> that means it can be <em>very lazily</em> initialized - if you call a static method which doesn't touch any fields, the JIT doesn't need to initialize the type.</p> <p><em>In practice</em> it means that the class is initialized <em>earlier</em> than it would be otherwise - it's okay for it to be initialized at the start of the first method which <em>might</em> use it. Compare this with types which <em>don't</em> have <code>beforefieldinit</code> applied to them, where the type initialization has to occur immediately before the first <em>actual</em> use.</p> <p>So, suppose we have:</p> <pre><code>public static void DoSomething(bool which) { if (which) { FirstType.Foo(); } else { SecondType.Bar(); } } </code></pre> <p>If both types have <code>beforefieldinit</code> applied to them (which in C# they do by default unless the type has a static constructor) then they'll <em>both</em> be initialized at the start of the <code>DoSomething</code> method (usually - it's not guaranteed). If they don't have <code>beforefieldinit</code> then only <em>one</em> of them will be initialized, based on the flag.</p> <p>This is why it's common to use a static constructor (even an empty one!) when <a href="http://csharpindepth.com/Articles/General/Singleton.aspx" rel="nofollow noreferrer">implementing the singleton pattern</a>.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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