C# Static constructor and default constructor call order

Asked 2 years ago, Updated 2 years ago, 40 views

class Person
{
    static public Person Instance = new Person("Jong");
    string name;

    static Person()
    {
        Console.WriteLine("static Person() Called!");
    }
   public Person(string _name)
    {
        name = _name;
        Console.WriteLine("Person Called!");
    }
    public void DisplayName()
    {
        Console.WriteLine(name);
    }

}
class Program
{
    static void Main(string[] args)
    {
        Person nPerson = new Person("ABCD");

    }
}

C# 7.1 For static fields in a class based on a book, if there is an initialization statement at the same time as the declaration, the compiler will be able to With only declarations left, the initialization syntax states that the code is generated and compiled by merging with the static constructor if it does not exist.

And when a static member is called for the first time or is created as an instance constructor, the static constructor runs before the instance constructor.

To find out when the static constructor was called in the above code

Console.WriteLine("static Person Called!");

That's the code

static public Person Instance = new Person("Jong");

The initialization part of the above code, the newPerson("Jong") source code, is merged with the static constructor to execute The execution result shows that the instance constructor of Instance -> Static constructor execution of Person -> nPerson's instance constructor execution.

So the source code is merged as below?

  static Person()
  {
       Instance = new Person("Jong");
       Console.WriteLine("static Person() Called!");
  }

So, no matter what code is in the static constructor, when merged, does the initialization syntax always take precedence over the existing code?

c#

2022-09-22 20:37

1 Answers

Yes, that's right.
If you think about what's intuitive from a programmer's point of view, you can also infer the order.
If the code of the static constructor is performed before the static field initialization, the value used for field initialization in the static constructor will not be available.
I said int a = 42; but when I read the value of a, if 0 came out, I wouldn't have programmed it.
Therefore, the order is

That's what happens. You can also find the official document that the field initialization code is performed before the generator's code.

The field is initialized immediately before calling the constructor for the object instance.


2022-09-22 20:37

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.