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 theset
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.– Roberto de Campos
In this specific case, as there is no extra treatment before assigning or returning, the second example is better.
– Roberto de Campos
https://answall.com/questions/15467/m%C3%A9todos-e-propriedades-em-c-vantagens-e-desvantagens/15474#15474
– Roberto de Campos