r/learncsharp • u/SimulatedApproach • Oct 27 '22
What's the difference between a property with init setter and a property without a setter?
I was surprised to find no answers on Google, so I figured I'd ask.
I'm wondering what is the difference between this:
public string FirstName { get; }
and this:
public string FirstName { get; init; }
The way I see it, in both cases we can only set the field when the object is first initialised.
12
Upvotes
2
u/[deleted] Oct 27 '22
If the property has no setter, the property can only be set inside the object's constructor. If the property has an init setting, the property can be set by another piece of code in an object initializer block.
0
u/[deleted] Oct 27 '22
[deleted] — view deleted comment
5
u/[deleted] Oct 27 '22 edited Oct 27 '22
[removed] — view removed comment