static readonly field initializer vs static constructor initialization

前端 未结 4 984
别跟我提以往
别跟我提以往 2020-12-02 13:16

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?

4条回答
  •  旧时难觅i
    2020-12-02 13:52

    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.

提交回复
热议问题