C# initialize static class member in the static constructor, otherwise, it will not be called

Lionsure 2020-08-23 Original by the website

In the process of program development, frequent use of some variables require resident memory, that is, they must be defined as static members, which will help reduce hard disk access and speed up program execution. If a certain variable is defined as a static member, and it is required to be initialized and assigned only once when the program starts to execute in C#. To meet this requirement, it is more appropriate to initialize in the constructor, and other methods require additional processing.

The question now is whether the variable is a static member, whether the initialized constructor should also be defined as a static constructor. The answer is yes. If the constructor is not defined as static, then the non-static constructor will not be executed when the program is executed for the first time.

 

1. C# static constructor not called when initialize static members in a non-static constructor

Suppose there is a class that defines the following static members and a constructor that initializes the static members:

public class TestStatic
       {
              public static string webName;
              public static string domain;

       private TestStatic()
              {
                     webName = "Computer Technology Website";
                     domain = "www.liangshunet.com";
              }

       public static void test()
              {
                     HttpContext.Current.Response.Write("webName=" + webName + "<br />domain=" + domain);
              }
        }

Call: TestStatic.test();

Output:

webName=
       domain=

Both static members are empty, indicating that the non-static constructor has not been executed. Changing the modifier of constructor to "public" will also not be executed.

 

2. C# initialize static class member in the static constructor and successfully initializes

Modify the above non-static constructor to:

static TestStatic()
       {
              webName = "Computer Technology Website";
              domain = "www.liangshunet.com";
       }

Call: TestStatic.test();

Output:

webName=Computer Technology Website
       domain=www.liangshunet.com

Both static members are assigned, indicating that the static constructor is successfully executed the first time the program is executed. This shows that if the static member is required to be automatically initialized when the program is executed for the first time, it must be completed in the static constructor, otherwise the constructor will not be executed, regardless of whether it is "private or public".