Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does beforefieldinit flag do?

Tags:

.net

cil

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?

like image 556
Embedd_0913 Avatar asked Mar 04 '09 14:03

Embedd_0913


People also ask

How are Initializers executed in C#?

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.

How many times of static constructor executes for a class?

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.


2 Answers

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.

like image 156
Jon Skeet Avatar answered Sep 30 '22 22:09

Jon Skeet


Looks like it is going to change in 4.6

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

like image 33
OmariO Avatar answered Oct 01 '22 00:10

OmariO