At what point are the properties calculated? C #

1

I'm using C # and I got the following doubt,

In a class in which I define a calculated read-only property, for example, a simple class

public class UnaClase
{
    public int Num1 { get; set; }
    public int Num2 { get; set; }
    public int Suma
    {
        get
        {
        return Num1 + Num2;
        }
    }

    public UnaClase(int num1,int num2)
    {
        Num1 = num1; Num2 = num2;
    }
}

At what moment in the life cycle of an instance of UnaClase will the calculation Num1+Num2 be made?

When creating the instance or each time I use the property?

    
asked by Juan Salvador Portugal 14.12.2018 в 15:28
source

2 answers

1

The calculation will apply when you access the property, since when accessing it you will go through its execution

This can be validated if you put a breakpoint in the code, when executing it will stop every time you access

You can still validate it with a simple example

UnaClase c1 = new UnaClase(10, 2);
txtResult.Text = c1.Suma.ToString();

c1.Num1 = 20;
txtResult.Text = c1.Suma.ToString();

You will see how when changing the property the sum is also affected

    
answered by 14.12.2018 / 21:13
source
0

Properties can also be defined as public "access points" to private data, either to obtain their value get , or to assign them value set . It is correct how much they already told you, they are evaluated at the moment of using them, again, whether you are assigning value or recovering it.

    
answered by 14.12.2018 в 16:35