static readonly field initializer vs static constructor initialization

14,805

Solution 1

There is one subtle difference between these two, which can be seen in the IL code - putting an explicit static constructor tells the C# compiler not to mark the type as beforefieldinit. The beforefieldinit affects when the type initializer is run and knowing about this is useful when writing lazy singletons in C#, for example.

In brief the difference is this:

.class private auto ansi beforefieldinit A
.class private auto ansi B

In all other aspects they are the same. Output from Reflector:

Class A:

.class private auto ansi beforefieldinit A
    extends [mscorlib]System.Object
{
    .method private hidebysig specialname rtspecialname static void .cctor() cil managed
    {
        .maxstack 8
        L_0000: ldsfld class [mscorlib]System.Collections.Generic.Dictionary`2<string, class Connection> WebConfigurationManager::ConnectionStrings
        L_0005: ldstr "SomeConnection"
        L_000a: callvirt instance !1 [mscorlib]System.Collections.Generic.Dictionary`2<string, class Connection>::get_Item(!0)
        L_000f: ldfld string Connection::ConnectionString
        L_0014: stsfld string A::connectionString
        L_0019: ret 
    }

    .method public hidebysig specialname rtspecialname instance void .ctor() cil managed
    {
        .maxstack 8
        L_0000: ldarg.0 
        L_0001: call instance void [mscorlib]System.Object::.ctor()
        L_0006: ret 
    }

    .field private static initonly string connectionString
} 

Class B:

.class private auto ansi B
    extends [mscorlib]System.Object
{
    .method private hidebysig specialname rtspecialname static void .cctor() cil managed
    {
        .maxstack 8
        L_0000: nop 
        L_0001: ldsfld class [mscorlib]System.Collections.Generic.Dictionary`2<string, class Connection> WebConfigurationManager::ConnectionStrings
        L_0006: ldstr "SomeConnection"
        L_000b: callvirt instance !1 [mscorlib]System.Collections.Generic.Dictionary`2<string, class Connection>::get_Item(!0)
        L_0010: ldfld string Connection::ConnectionString
        L_0015: stsfld string B::connectionString
        L_001a: ret 
}

    .method public hidebysig specialname rtspecialname instance void .ctor() cil managed
    {
        .maxstack 8
        L_0000: ldarg.0 
        L_0001: call instance void [mscorlib]System.Object::.ctor()
        L_0006: ret 
    }


    .field private static initonly string connectionString    
}

Solution 2

The beforefieldinit attribute indicates how the initialization happens.

In case of an explicit static constructor initialization, the initialization of the static member happens the moment the type is accessed. In the example given in case of class A, the initialization will happen only when connectionString is first referred, whereas in case of class B initialization will happen the first time the type class B is referred, not necessarily accessing connectionString.

Only C# (.NET 4.0 ) provides us control over how static members can be initialized. With VB.NET only the non beforefieldinit method is possible whereas with C++/CLI only the beforefieldinit mechanism is possible.

Solution 3

They are essentially the same, but if you happen to have both a read-only assignment to a static field and a static type constructor, the read-only assignment occurs first.

Solution 4

I have to add that with explicit constructor present (non beforefieldinit version) accessing static members are comparatively way slower.

From https://rules.sonarsource.com/csharp/RSPEC-3963

When a static constructor serves no other purpose that initializing static fields, it comes with an unnecessary performance cost because the compiler generates a check before each static method or instance constructor invocation.

Instead, inline initialization is highly recommended.

Share:
14,805

Related videos on Youtube

stackoverflowuser
Author by

stackoverflowuser

Updated on November 15, 2021

Comments

  • stackoverflowuser
    stackoverflowuser over 2 years

    Below are two different ways to initialize static readonly fields. Is there a difference between the two approaches? If yes, when should one be preferred over the other?

    class A
    {
        private static readonly string connectionString =
            WebConfigurationManager.ConnectionStrings["SomeConnection"].ConnectionString;
    }
    
    class B
    {
        private static readonly string connectionString;
    
        static B()
        {
            connectionString =
                WebConfigurationManager.ConnectionStrings["SomeConnection"].ConnectionString;
        }
    }
    
  • Sivaram K
    Sivaram K almost 4 years
    "In the example given in case of class A, the initialization will happen only when connectionString is first referred" - I believe this can be generalized as " the initialization will happen only when any of the static fields of class A is first referred"