Difference between property declaration in C#

Asked

Viewed 64 times

2

I’m studying C#, very beginner, and I came across something, the course I’m doing has video lessons from 2015, and it passes me to create a class with attributes and properties like this: (Tabulations and blank lines are a preference for me to "find myself" in the code)

class ProgramaTeste {

       protected int _numero;

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

However, in another question here on the site, I was told that these statements are outdated and that I should use this way:

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

It’s definitely optimized and better, but doesn’t this compromise the encapsulation? Because I’m not declaring the variable as protected.

  • There’s nothing out of date there, if you need a special treatment at get or in the set only the first example will work. If you don’t need a special treatment the second example is better. Remembering that if one day you need to switch from the first to the second, you will get.

  • In this specific case, as there is no extra treatment before assigning or returning, the second example is better.

  • https://answall.com/questions/15467/m%C3%A9todos-e-propriedades-em-c-vantagens-e-desvantagens/15474#15474

1 answer

4


NO C# 3.0 has been implemented the self implemented properties this gives us the power to declare the properties of a class of no additional logic in the assessors (get and set) of the properties.

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

When using the syntax of the auto-implemented properties the C# compiler generates automatically the private camps.

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

Take another read on this source: Macoratti

Browser other questions tagged

You are not signed in. Login or sign up in order to post.