Difference between declaration of properties in C # [duplicate]

2

I'm studying C #, quite a beginner, and I came across one thing, the course I'm doing has video lessons from 2015, and it passes me to create a class with attributes and properties this way: (Tabs and blank lines are my preference to "find me" in the code)

class ProgramaTeste {

       protected int _numero;

       public int numero {
              set{ _numero = value; }
              get{ return _numero; }
       }
}

But in another question here on the site, I have been told that these statements are outdated and that I should use it this way:

class ProgramaTeste {
       public int numero{ get; set: }
}

Sure enough it's optimized and better, but does not this compromise the encapsulation? For I am not declaring the variable as protected.

    
asked by anonymous 17.10.2018 / 15:31

1 answer

4

In C # 3.0 the self-implemented properties feature has been implemented, this gives us the power to declare the properties of a class with no additional logic in the get and set properties

In the properties access methods we have the famous get / set, where the get accessor is responsible for returning a value from a private class field and the set accessor is responsible for assigning a new value to the field.

By using the syntax of self-implemented properties, the C # compiler automatically generates private fields.

That is: using this feature we have a reduction in the amount of code needed to implement the properties of our classes and the code becomes clearer and more readable.

Read more at this source: Macoratti

    
17.10.2018 / 15:40