Create and use Value Objects
Create a new value object by decorating a partial type with the ValueObject
attribute:
The type must be partial
as the source generator augments the type with another partial class containing the generated code.
Now, create a new instance by using the From
method:
If you try to use the constructors, the analyzer rules will catch this and stop you.
You can now be more explicit in your methods with signatures such as:
If your type has validation, then the From
method will throw an exception if validation fails.
This stops invalid instances being created, but exceptions might not be desirable. In this case, use the TryFrom
method. There are two overloads for this. One returns a ValueObjectOrError<T>
and one returns a bool and takes an out
parameter.