8
I was reading about the new implementations on C# 9
and came across the init
, init-only-setters:
Starting with C# 9.0, you can create init accessors Instead of set accessors for properties and indexers.
In free translation:
From C# 9.0, you can create "advisors"
init
instead of define advisorsset
for properties and indexers.
Viewing the code example below:
public class Pessoa
{
public string Nome { get; init; }
public string Idade { get; set; }
}
You can instantiate the class like this, "in the constructor":
var pessoa = new Pessoa
{
Nome = "Fulano",
Idade = 20
};
The estate Idade
can be changed after the instance, but not the property Nome
:
pessoa.Nome = "Outro"; // isso dá erro
That’s not the same as declaring ownership Nome
this way?
public string Nome { get; private set; }
If so, is there any advantage in using the init
in place of private set
?
It is good to note that in this answer I talk about the differences between the utilizing of the modifiers. If we are talking about the generated IL the init is much more like the set (he is indeed a method Setter - I even think he’s a Setter public which has access controlled at compilation level only).
– Jéf Bueno
good response, then the
private set
is something that can only be modified in the private scope of the class, whether in construction or not, and theinit
only by instantiating the object is this?– Ricardo Pontual
That’s it right there.
– Jéf Bueno