SoFunction
Updated on 2025-03-07

Detailed explanation of the constructor method of c# class

1. Construction method

The class constructor is a type of class member method, and its function is to initialize members in the class. Class constructors are divided into:

1. Static construction method

2. Example construction method

1. Static construction method

The static constructor of a class is a type of class member method, and its function is to initialize static members in the class. Please see the code example below:

using System;
namespace LycheeTest {
 class Test {
 //Define a static member variable private static int a;
 //Define static constructor static Test() {
  //Initialize static member variable  a = 11;
 }
 public void Show() {
  ("Static fields a The value is:{0}", a);
 }
 }
 class Program {
 static void Main(string[] args) {
  Test t = new Test();
  ();
  ();
 }
 }
}

First, the above code defines two classes. Line 3 code defines the class Test. When defining a class, there are two access rights modifiers for the class, one is public and the other is internal. When no access modifier is written, the access permissions of the class are internal by default. The meaning of this access permission is that this class can only be accessed by this assembly and cannot be accessed by classes other than this assembly. If this class belongs to the class library, it must be public, otherwise the assembly calling it cannot access it. Line 5 code defines a static field member, and line 7 code is a static constructor. It can be seen that the characteristic of the static constructor is that the static keyword indicates that the method is static, the method name should be exactly the same as the class name, and pay attention to upper and lower case here.Static construction methods cannot contain parameters, and static construction methods cannot have return values. The operation of initializing static members can be performed in the body of the static construction method. Line 11 defines an instance method, which is used to output the value of the static field. This class is called in the Main (note: it is main in java) method in the class Program on line 16, line 18 creates an instance of this class, and line 19 calls the instance method of the class.

As can be seen from the above code, there is no explicit call to the static constructor of the class.

Please see the execution results of the above code below:

The value of the static field a is: 11

As can be seen, the static construction method is indeed executed. Then the above example is one of the execution conditions of the static constructor method. When the class instance is created, the static constructor method of the class will be automatically called.

The order of call to the static constructor is after the initial value setting of the static field.

That is, the first step is to set the default value of the static field, the second step is to execute the initial value setting item of the static field, and the third step is to call the static constructor of the class.

The following is the previous code example, the code is as follows:

using System;
namespace LycheeTest{
 class Test {
 private static int a;
 static Test() {
  a++;
 }
 public void Show() {
  ("Static fields a The value is:{0}", a);
  14
 }
 }
 class Program {
 static void Main(string[] args) {
  Test t = new Test();
  ();
  Test t1 = new Test();
  ();
  ();
 }
 }
}

This code has modified the static constructor method and auto-increment the static field a in the method body. Then, on line 17 of the code, another instance of the class is created, and the instance method of the class is called again.

Let's see the execution results below:

Static fields a The value is:1 
Static fields a The value is:1

As you can see, the value of the static field has not increased. This is the characteristic of the execution of static constructor methods, which is executed only once. When the assembly is run, an application domain will be created, and in an application domain, the static constructor of the class is only executed once.

The following is the following modification to the code example:

using System;
namespace LycheeTest {
 class Test {
 public static int a;
 static Test() {
  ("The static constructor of the class starts executing");
  a++;
 }
 public void Show() {
  ("Static fields a The value is:{0}", a);
 }
 }
 class Program {
 static void Main(string[] args) {
  ("Static fields a The value is:{0}", );
  ("Static fields a The value is:{0}", );
  ();
 }
 }
}

This code prints out a line of markers in the static constructor of the class, and the access permissions of the static fields of the class are also modified to public, which allows it to be called outside the class. The value of the static field is printed twice in the Main method. Note that calling the static field of the class outside the class requires reference to the class name.

Here is the execution result of the code:

The static constructor of the class begins execution
Static fields a The value is:1
Static fields a The value is:1

This code does not create an instance of the class. The static constructor of the class will be called before referring to the static member of the class. The static members of the called class include static fields and static methods. This is the second condition for the static constructor method call of the class.

The following is the following modification to the code example:

using System;
namespace LycheeTest {
 class Program {
 private static int a;
 static Program() {
  ("The static constructor of the class is called");
  a = 11;
 }
 static void Main(string[] args) {
  ("The Main method is called");
  ("Static fields a The value is:{0}", a);
  ();
 }
 }
}

This code defines static fields and static constructors in the class containing the Main method. Because the Main method is also a static method, the static constructor of the class is called and it is the entry point method of the class, so who calls it first between it and the static constructor of the class? Let’s first look at the execution results of the code:

The static constructor of the class is called
Main Method is called
Static fields a The value is:11

Through the execution results of the code, we can see that because the entry point method of the class is still a static method, the static constructor is called first before any static member is called. Therefore, it can be concluded that the static constructor of a class is called before the Main method of the class.

So can the static constructor of the class be called explicitly? Let's see the code example below:

using System;
namespace LycheeTest {
 class Program {
 private static int a;
 static Program() {
  ("The static constructor of the class is called");
  a = 11;
 }
 static void Main(string[] args) {
  Program();
  ();
 }
 }
}

Line 10 of this code explicitly calls the static constructor of the class, and the compiler will report an error.

2. Instance constructor

The instance constructor of a class is a class member method, and its function is to initialize the instance members of a class. An instance constructor can implement overloading. When creating an instance of a class, different parameters can be explicitly specified to call different instance constructors of overloading. Please see the code example below:

using System;
namespace LycheeTest {
 class Program {
 private static int a;
 private int b = 12;
 private string c = "Hello World";
 static Program() {
  ("The static constructor of the class is called");
  a = 11;
 }
 public Program(int a, string s) {
  ("Constructor method with two parameters is called");
   = a;
   = s;
 }
 public Program(int a) : this(a, "Calling a constructor through this keyword") {
  ("Constructor with one parameter is called");
 }
 public void Show() {
  ("Static fields a The value is:{0}", a);
  ("Instance Field b The value is:{0}", b);
  ("Instance Field c The value is:{0}", c);
 }
 static void Main(string[] args) {
  Program p1 = new Program(33, "This is the instance P1 created");
  Program p2 = new Program(34);
  ();
  ();
  ();
 }
 }

Lines 4, 5 and 6 of this code define three field members, line 4 is a static field, and line 5 and 6 have initializers. Line 8 of the code is the definition of an instance constructor. The instance constructor also takes the class name as the method name, and it has no return value. The method name is an access permission modifier. The access permission modifiers that can be used include public, private and protected. The protected means that the constructor can only be accessed internally in this class. The example construction method can take parameters. The instance constructor of line 12 code uses two incoming parameters to assign the instance field. Line 17 defines an instance constructor with one parameter, which forms an overload with the previous instance constructor. The instance constructor can call other instance constructors through this keyword. The method is to use a colon after the parameter list and then follow the parameter list, and then follow the parameter list. This parameter list must match another overloaded instance constructor. The constructor in line 17 has only one parameter, which passes this parameter to another constructor through this keyword. When calling another constructor with this, a string parameter is passed to it at the same time. The instance method in line 24 prints the value of the field member of the class. In the Main method, line 26 and line 27 define two instances, which use the new keyword to call different instance constructors. Lines 28 and 29 respectively call the instance method to print the static field of the class and the values ​​of the two field members of the instance.

Let’s first look at the execution results of the code:

The static constructor of the class is called The constructor with two parameters is called The constructor with two parameters is called The constructor with one parameter is called 
Static fields a The value is:11 
Instance Field b The value is:33
Instance Field c The value is:This is the instance created P1 Static fields a The value is:11
Instance Field b The value is:34
Instance Field c The value is:pass this Keyword call constructor

Now use the execution result to introduce the execution process of the instance construction method. When the 26th line of code creates an instance of the class, the static field of the class is first set to the default value. Since there is no initial value setting item for the field, the static construction method of the class is then executed. At this time, the static field a is set to 11. Because line 26 code uses new to call the instance constructor with two parameters, first instance field b is set to 0 and instance field c is set to null. Then execute the initial value setting item of the field, b is assigned to 12, and c is assigned to "Hello World". Next, execute the first statement in the example constructor body, and the string "The constructor with two parameters is called" is printed. Next, field b of example p1 is set to the passed parameter 33. Note that the formal parameter a of the constructor overrides the static field a of the class here. That is to say, the local variable a of the example construction method is at this time. The instance field c is then set to the string "This is the instance P1 created". Line 27 uses the new keyword to call the instance constructor with one parameter. When calling, the instance field b belonging to p2 is first set to 0 and the instance field c is set to null. Then execute the initial value setting item of the field, b is assigned to 12, and c is assigned to "Hello World". Next, this referenced instance constructor with two parameters, the string "Constructor with two parameters is called" is printed. Then b is set to 34 and c is set to "call the constructor through this keyword". Finally, the code control returns to execute the print statement in the instance constructor body with one parameter, and the string "Constructor with one parameter is called" is printed. At this point, the execution of the example construction method is completed. The next code prints the value of the static field. You can see that the static field values ​​printed by the two instances are the same, but the values ​​of their instance fields are different.

Optional parameters and named parameters can also be used for instance construction methods. Let’s see the code example below:

using System;
namespace LycheeTest {
 class Program {
 private int b;
 private string c;
 public Program(int a = 12, string s = "") {
   = a;
   = s;
 }
 public void Show() {
  ("Instance Field b The value is:{0}", b);
  ("Instance Field c The value is:{0}", c);
 }
 static void Main(string[] args) {
  Program p1 = new Program(); // Both parameters of the construction method use default values  Program p2 = new Program(34); //The string type parameter of the constructor uses the default value  Program p3 = new Program(23, "Hello World"); //The two parameters of the construction method use incoming parameters  Program p4 = new Program(s: "The weather is so good today"); //Use named parameters, another parameter a  ();
  ();
  ();
  ();
  ();
 }
 }
}

Line 6 of the code defines a constructor with optional parameters and named parameters, and then creates an instance of a class, and no parameters are passed in the constructor. At this time, both parameters of the constructor use the default value. Line 16 code passes in an int parameter for the constructor. At this time, another parameter of type string adopts the default value. Line 17 passes in two parameters, and both parameters of the construction method use these two passed parameters. Line 18 uses a named parameter to specify that the passed in parameter is a parameter of type string and pass it to the formal parameter s. At this time, another parameter of type int adopts the default value. Lines 19 to line 23 code prints the value of the instance field of the class. The execution result of this code is as follows:

Instance Field b The value is:12 
Instance Field c The value is: 
Instance Field b The value is:34 
Instance Field c The value is: 
Instance Field b The value is:23
Instance Field c The value is:Hello World Instance Field b The value is:12
Instance Field c The value is:The weather is so good today

The above is all the content of this article. I hope that the content of this article will help you study or work. I also hope to support me more!