Search code examples
c#.netclrcilstatic-initialization

How does the CLR know if a static field has already been initialized?


There is one thing I have been always been wondering about static fields / constructors.

The static class initialized the first time one of it's fields is referenced, that is easy.

But how does the CLR know that it is the first time?


Solution

  • The CLR maintains a table of all types that have been loaded and their initialization status. If A is using a static field of B then the CLR knows that A is using B and while initializing A it will also initialize B. So the check if dependencies are initialized is not performed on each access. It is ensured though dependency graph of the types.

    If you are interested in the implementation details you can have a look at the IsClassInitialized method of the DomainLocalModule in CoreCLR and its usage when instances of classes are created.

    I hope this answers your question.