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?
Initializers execute before the base class constructor for your type executes, and they are executed in the order in which the variables are declared in your class. Using initializers is the simplest way to avoid uninitialized variables in your types, but it's not perfect.
Times of Execution: A static constructor will always execute once in the entire life cycle of a class. But a non-static constructor can execute zero time if no instance of the class is created and n times if the n instances are created.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With