What is the difference between these two types of standard definition? [duplicate]

1

In C # , when creating a new classe with some properties, I must set some default value for the created properties, 0 in case of a property of Current Balance .

What would be the difference between the two following ways that represent the above situation? Would you have any future problems with using the first or the second? Which would be the best?

First way:

using System;

public class Correntista
{
    public double SaldoAtual { get; set; } = 0;
    public string Nome { get; set; }
}

Second way:

using System;

public class Correntista
{
    public Correntista()
    {
        SaldoAtual = 0;
    }

    public double SaldoAtual { get; set; }
    public string Nome { get; set; }
}
    
asked by anonymous 17.10.2018 / 19:47

1 answer

4

In practice there is no difference. The default value for the property will be inserted into the builder call.

However, by analyzing the two generated IL codes, one can notice a brief difference between the two. See below the code for the constructor method generated for the two cases.

Case 1 - Value entered in the constructor:

Correntista..ctor:
IL_0000:  ldarg.0     
IL_0001:  call        System.Object..ctor
IL_0006:  nop         
IL_0007:  nop         
IL_0008:  ldarg.0     
IL_0009:  ldc.i4.0    
IL_000A:  call        UserQuery+Correntista.set_SaldoAtual
IL_000F:  nop         
IL_0010:  ret   

Case 2 - Default value for property:

Correntista..ctor:
IL_0000:  ldarg.0     
IL_0001:  ldc.i4.0    
IL_0002:  stfld       UserQuery+Correntista.<SaldoAtual>k__BackingField
IL_0007:  ldarg.0     
IL_0008:  call        System.Object..ctor
IL_000D:  nop         
IL_000E:  ret     

Have you noticed that there are two small differences between them?

In the first case, the base class ( Object ) is called first and then the constructor uses the set_SaldoAtual method to change the value of the field.

In the second case, the value of the field is initially changed, but without making use of the set_SaldoAtual method, the value is inserted directly into the "support field" backing field ).

This really should not change anything in practice because only auto-properties can have a default value. In this way, the implementation of the set_SaldoAtual method will always only make the backing field receive the value passed to the method.     

17.10.2018 / 20:19