What are the benefits of initializing field defaults in C-sharp using a method similar to the CPP delegate constructor?

in CLR via C-sharp, it is mentioned that calling a common initialization constructor reduces the amount of code generated (164pages).
the following code, which the book says, because there are three constructors, compiles and generates three times the code that initializes m _ constructor _.

class SomeType
{
    private Int32 m_x = 5;
    private String m_s = "Hi";
    private Double m_d = 3.14;
    private Byte m_b;

    public SomeType() { }
    public SomeType( Int32 x) { }
    public SomeType( String s) {  ...;  m_d = 10; }
}

while the following code uses a common initialization constructor to reduce the generated code. Excuse me, why does this reduce the generated code?
the public initialization constructor will also be called three times, so it will still initialize minitix, minitism, and minitid three times.

class SomeType
{
    private Int32 m_x ;
    private String m_s ;
    private Double m_d;
    private Byte m_b;

    public SomeType() {
          m_x = 5;
          m_s = "Hi";
          m_d = 3.14;
}
    public SomeType( Int32 x) :this(){
        m_x = x;
    }
    public SomeType( String s):this() {
        m_s = s;
    }
    public SomeType( Int32 x,String s):this()
    {
        m_x = x;
        m_s = s;
    }
}
Nov.27,2021

only the common constructor initializes three fields at the same time, while only individual fields are initialized within the other constructors, and there is no code to initialize all of them.

three fields are initialized in each constructor in the previous writing, so the exact same initialization code is repeated several times.

in fact, this is equivalent to extracting the logic that will be used in several functions into a separate function for other functions to call, thus reducing repetitive code.

  • How to allocate memory in C-sharp

    see the garbage collection principle of C-sharp on the Internet, using the concept of big and small heap and generation, big and small heap is easy to understand. As far as I understand it, every time there is no recycling, it is pressed to the next gene...

    Oct.25,2021
Menu