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?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
See my article on this very issue.
Basically,
beforefieldinitmeans ‘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
beforefieldinitapplied to them, where the type initialization has to occur immediately before the first actual use.So, suppose we have:
If both types have
beforefieldinitapplied 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 theDoSomethingmethod (usually – it’s not guaranteed). If they don’t havebeforefieldinitthen 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.