'Get-Init Property vs Get-Only Property in C# [duplicate]
What would the difference in these two code snippets? Both compiles fine with .NET Core 6.
public class Person
{
public string FirstName { get; init; }
public Person(string firstName)
{
FirstName = firstname;
}
}
vs
public class Person
{
public string FirstName { get; }
public Person(string firstName)
{
FirstName = firstname;
}
}
Solution 1:[1]
The init accessor makes immutable objects more flexible by allowing the caller to mutate the members during the act of construction. That means the object's immutable properties can participate in object initializers and thus remove the need for all constructor boilerplate in the type.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
