C# Static constructor does not allow access modifier examples(static function)

Lionsure 2020-08-15 Original by the website

Functions(methods) have three access modifiers in C#, namely: public, protected, and private; generally speaking, modifiers are required in front of functions to determine the scope of access to it, while static constructors are just the opposite. No access modifiers are allowed in front of it, otherwise an error will be reported during compilation.

Constructor is a method used to initialize members in a class. When the class is executed for the first time, the constructor is executed first and executed only once, that is, it is no longer executed after completing the task of initializing members. Sometimes, some variables are often used, so they need to be defined as static members to make them resident in memory to improve execution speed. The initialization of static members must be in the static constructor, so classes with static members need to define a static constructor. The following are the cases where the access modifier is added and not added in front of the static constructor.

 

1. Add access modifier before static constructor in C#

Define a StaticTest class, and then define several static members, and then initialize these static members in the static constructor, the code is as follows:

public class StaticTest
       {
              public static string configFile;
              public static string imgPath;

       public static StaticTest()
              {
                     configFile = "Value comes from database";
                     imgPath = "Value comes from database";
              }
       }

An exception is thrown immediately during compilation, prompting: access modifiers are not allowed in static constructors. This prompt has a double meaning and is very easy to confuse, whether it refers to static member variables or static constructor itself.

 

2. C# Static constructor does not allow access modifier

Remove the access modifier before the above class, the code becomes:

class StaticTest
       {
              public static string configFile;
              public static string imgPath;

       public static StaticTest()
              {
                     configFile = "Value comes from database";
                     imgPath = "Value comes from database";
              }
       }

When compiling again, the error "Access modifier is not allowed in static constructor" will not be reported, indicating that access modifier is not allowed before static constructor, not static member variables.