title: Validation of a C# object initialized with init-only setters
body: <hr />
  <h2>Disclaimer for re-opening</h2>
  <p>This question is about <strong>object validation</strong> of an <strong>immutable</strong> object <strong>during construction</strong> using C# 9 <a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-9.0/init" rel="noreferrer">init-only setters</a> (as opposed to using a <em>constructor</em> with verbose <em><a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-9.0/init" rel="noreferrer">&quot;boiler plate code&quot;</a></em>).</p>
  <hr />
  <p>C# 9 introduces an option to initialize immutable object with object initializer syntax, using init only setters:</p>
  <pre class="lang-cs prettyprint-override"><code>class Immutable
  {
     public string Name { get; init; }
     public int Value { get; init; }
  }
  
  Immutable o = new Immutable { Name = &quot;Value1&quot;, Value = 257 };
  </code></pre>
  <p>Additionally it introduces a nice syntax to create mutated copies of an object:</p>
  <pre class="lang-cs prettyprint-override"><code>var o1 = o with { Value = 65537 };
  </code></pre>
  <p>Previously the only option to create and initialize a new immutable object was to use constructor with parameters. The new option is more natural and elegant, but one important feature of constructor initialization is missing: validation. With constructor I can be sure to never create an object with invalid state.</p>
  <p>It is possible to put validation code into init setters, but there's no way, of which I'm aware of, to provide a general validation of object state as a whole. Specifically, I don't see any way to assure in the example above that <code>Name</code> property will fulfill its contract to have a non-null value. As parameterless constructor is necessary to use object initializer syntax, it is possible to create an uninitialized instance:</p>
  <pre class="lang-cs prettyprint-override"><code>var o = new Immutable();
  </code></pre>
  <p>in which case properties will get default values.</p>
  <p>Question [edit]: is there any method to validate immutable object state after initialization with init setters is complete? Keep in mind that property assignments may be not specified in the initialization statement and the default object state may be invalid.</p>