Jacek Ostrowski
Jacek Ostrowski

Reputation: 89

Validation of a C# object initialized with init-only setters


Disclaimer for re-opening

This question is about object validation of an immutable object during construction using C# 9 init-only setters (as opposed to using a constructor with verbose "boiler plate code").


C# 9 introduces an option to initialize immutable object with object initializer syntax, using init only setters:

class Immutable
{
   public string Name { get; init; }
   public int Value { get; init; }
}

Immutable o = new Immutable { Name = "Value1", Value = 257 };

Additionally it introduces a nice syntax to create mutated copies of an object:

var o1 = o with { Value = 65537 };

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.

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 Name 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:

var o = new Immutable();

in which case properties will get default values.

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.

Upvotes: 6

Views: 3022

Answers (1)

Jacek Ostrowski
Jacek Ostrowski

Reputation: 89

I've finally found the information on validation in Mads Torgersen's comment under his post on C# 9. They are looking into options to introduce this in C# 10.

[Edit] If was finally, at least partially, resolved in C# 11 by introduction of required keyword, which can be used on properties. This is quite elegant solution, because it forces assignment on source code level (IDE hilights missing assignments). Still, ability to run some code after all assignments have been made would be useful.

Upvotes: 1

Related Questions