0

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;
  }
}
rencedm112
  • 397
  • 3
  • 11
  • 2
    `init` properties have the potential to violate guarantees made by a class constructor - so they should only be used for trivial and _optional_ state. – Dai Feb 18 '22 at 06:04

1 Answers1

-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.

For more information read this Doc

Salar Afshar
  • 229
  • 1
  • 2
  • 13
  • This isn't true - `init` properties in object-initializers run **after** the constructor, not "during" - and it **does not** remove the need for constructor code because constructors still serve a valuable purpose: to make hard guarantees about the state of an object, whereas `init`-properties do not. – Dai Feb 18 '22 at 06:09
  • @Dai, well no one says constructors are not valuable, in this sample code he can remove constructor for initialization properties and also can use object initialization normally. – Salar Afshar Feb 18 '22 at 06:48