0

Lets say we have the following class.

public class Person
{
    public string FirstName { get; init; }
    public string LastName { get; init; }
}

This would enforce us to set both properties. However.. Lets say we dont want to allow the value to be null, or maybe even not allow the FirstName to start with the letter/char "A" or enforce the names to start with a char in upper case. (guard the values)

We could create add a constructor that takes zero arguments, however.. Then we no longer will get a "heads up" by the compiler/IDE that a few props needs to be set.

How would you "guard" values when using init?

Inx51
  • 1,911
  • 3
  • 24
  • 44
  • 1
    The only way to guarantee values are set is with constructor, not `init` properties. `init` properties should only be used for properties representing state that is _optional-at-init-time_ state. – Dai Dec 02 '21 at 11:37
  • 1
    See my answer to this question: https://stackoverflow.com/a/70077377/159145 – Dai Dec 02 '21 at 11:39
  • FWIW, you _can_ have property setter bodies with `init` properties - where you can have your validation logic before mutating state. I think you're confusing shorthand "auto-properties" with `init` properties - they're orthogonal concepts: you can use `init` with shorthand and longhand properties. – Dai Dec 02 '21 at 11:40
  • Oh I see! Guess its back to arguments :). – Inx51 Dec 02 '21 at 11:46

0 Answers0