The accepted answer is correct; the initialization will happen either zero or one times but never twice. But I would add a caveat. In your example the CLR and the C# language reserve the right to initialize the field earlier than you might expect. If you write:
public class MyClass
{
private static readonly Dictionary<string,int> mydict = CreateDictionary();
static MyClass() {}
then the CLR and C# guarantee that the field will be initialized when the first static method is called on MyClass
or when the first instance of MyClass
is created. If you omit the static constructor then the CLR and C# are permitted, but not required, to initialize the field at any time prior to those events. In particular, suppose you have a method M
which calls a static method of MyClass
. The CLR might decide to run the static initializer of MyClass.mydict
when M
is jitted, and not when M
actually calls the static method. This can in some rare situations lead to surprising results.
Do a web search on the beforefieldinit
optimization for more details. Jon Skeet has a good article on this.