What does beforefieldinit flag do?

What does beforefieldinit flag do? When I look into the IL of my class I see this flag but I don't know what this flag is actually doing?


See my article on this very issue.

Basically, beforefieldinit means "the type can be initialized at any point before any static fields are referenced." In theory that means it can be very lazily initialized - if you call a static method which doesn't touch any fields, the JIT doesn't need to initialize the type.

In practice it means that the class is initialized earlier than it would be otherwise - it's okay for it to be initialized at the start of the first method which might use it. Compare this with types which don't have beforefieldinit applied to them, where the type initialization has to occur immediately before the first actual use.

So, suppose we have:

public static void DoSomething(bool which)
{
    if (which)
    {
        FirstType.Foo();
    }
    else
    {
        SecondType.Bar();
    }
}

If both types have beforefieldinit applied to them (which in C# they do by default unless the type has a static constructor) then they'll both be initialized at the start of the DoSomething method (usually - it's not guaranteed). If they don't have beforefieldinit then only one of them will be initialized, based on the flag.

This is why it's common to use a static constructor (even an empty one!) when implementing the singleton pattern.


Looks like it is going to change in 4.6

https://github.com/dotnet/coreclr/issues/1193