Jacobi.ValueObject 1.1.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package Jacobi.ValueObject --version 1.1.0
                    
NuGet\Install-Package Jacobi.ValueObject -Version 1.1.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Jacobi.ValueObject" Version="1.1.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Jacobi.ValueObject" Version="1.1.0" />
                    
Directory.Packages.props
<PackageReference Include="Jacobi.ValueObject" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Jacobi.ValueObject --version 1.1.0
                    
#r "nuget: Jacobi.ValueObject, 1.1.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Jacobi.ValueObject@1.1.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Jacobi.ValueObject&version=1.1.0
                    
Install as a Cake Addin
#tool nuget:?package=Jacobi.ValueObject&version=1.1.0
                    
Install as a Cake Tool

Value Object

Read more on what a Value Object is here (wikipedia).

*) Currently Jacobi.ValueObject only supports single values - one field.

The assumption in the implementation is:

  • A ValueObject is immutable. The code generation adds the readonly modifier (so you don't have to).
  • A ValueObject is compared by content/value - not by reference. Basic struct behavior in dotnet.
  • A valid ValueObject never contains a value of null. So do not specify nullable types as 'datatype'.

Usage

Add a (package) reference to Jacobi.ValueObject.

using Jacobi.ValueObject;

The ValueObjectAttribte works on both partial struct and partial record struct declarations.

  • partial struct: The IEquatable<ValueObject> interface is automatically added and implemented.
  • partial record struct: The IEquatable<ValueObject> interface is added and implemented by the compiler (because record).

Two attribute syntax variations:

[ValueObject<Guid>]
public partial record struct ProductId;

[ValueObject(typeof(Guid))]
public partial struct ProductId;

We call the Guid the 'datatype' and the ProductId the 'ValueObject'.

Minimal effort:

[ValueObject<Guid>]
public partial struct ProductId;

...

var prodId = new ProductId(Guid.NewGuid());

Using Options to manage what code (support) is generated.

[ValueObject<Guid>(Options = ValueObjectOptions.Parsable)]
public partial record struct ProductId;

...

var prodId = ProductId.Parse("<guid>", null); // no format provider

Implement validation by providing a static bool IsValid(<datatype> value) method. You determine the accessibility (public, internal, private).

[ValueObject<Guid>]
public partial record struct ProductId
{
    public static bool IsValid(Guid id) => id != Guid.Empty;
}

...

var prodId = new ProductId(Guid.Empty);   // <- will throw

Options

Option Description
Constructor Makes the value-constructor public. This option is default if none are specified.
ImpicitFrom Adds an implicit assignment operator that allows assigning the <datatype> value to a new instance of the ValueObject. Additionally an implementation for the IEquatable<datatype> interface will also be generated.
ImplicitAs Adds an implicit assignment operator that allows assigning the ValueObject to a <datatype> variable. Additionally an implementation for the IEquatable<datatype> interface will also be generated.
ExplicitFrom Adds a static factory method From that construct a new ValueObject instance from a specified <datatype> value.
ToString Overrides the record struct dotnet implementation to return the ValueObject.Value as string.
Comparable Implements the IComparable<ValueObject> interface to compare between ValueObject instances. If ImplicitFrom and/or ImplictAs options are also active, an implementation for IComparable<datatype> is also generated.
Parsable Implements the IParsable<ValueObject> and ISpanParsable<ValueObject> interfaces to provide Parse and TryParse methods. Note that this option cannot be used in combination with a <datatype> of string (System.String).

As an alternative there is also an option to declare the interfaces explicitly and forgo specifying options.

The folowing interfaces are supported:

Interface Description
IEquatable<datatype> Implements the IEquatable<T> interface for the datatype, as you get with the implicit-options.
IComparable<ValueObject> Implements the IComparable<T> interface for the ValueObject, as if the Comparable option was specified.
IComparable<datatype> Implements the IComparable<T> interface for the datatype, as if the Comparable option was specified together with one of the implicit-options.
IParsable<ValueObject> Implements the IParsable<T> interface for the ValueObject (but not ISpanParsable<T>), as if the Parsable option was specified.
ISpanParsable<ValueObject> Implements the ISpanParsable<T> interface for the ValueObject (including IParsable<T>), as if the Parsable option was specified.

Note that IEquatable<ValueObject> is always present. Either generated by the compiler when using a record struct or by Jacobi.ValueObject when using struct.

Methods

Implement a static bool IsValid(<datatype> value) method in your ValueObject and it will be detected and used when constructing new instances.

[ValueObject<Guid>]
public partial record struct ProductId
{
    // public, internal or private - you decide
    public static bool IsValid(Guid id) => id != Guid.Empty;
}

Declare a public static partial bool From(<datatype> value); partial method (no implementation) in your ValueObject and it will be detected and implemented similar to specifying the ExplicitFrom option.

[ValueObject<Guid>]
public partial record struct ProductId
{
    public static partial ProductId From(Guid id);
}

Exceptions

The Jacobi.ValueObject.ValueObjectException is throw in these circumstances.

  • The default (parameterless) constructor of the ValueObject is called.
  • The Value property is accessed while the instance of the ValueObject was not correctly initialized.
  • If the ValueObject implements the IsValid static method and the value fails the test.

Project File

To see the generated source files for the value objects, add to your .csproj project file:

<PropertyGroup>
  <EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
</PropertyGroup>

Compiler Errors

Code Error
VO001 You have declare a ValueObject in the global namespace. It is mandatory to declare your ValueObjects inside a namespace.
VO002 You did [ValueObject(null)] - It cannot work without a datatype.
VO003 You used the Parsable option on a ValueObject with the string/Systsem.String datatype.

CSXXXX Compiler errors caused by you not following the rules 😃

  • Do not specify a default constructor. So do NOT do this: public partial record struct ProductId()
  • Do not use the ToString option and also implement a string ToString() override in your ValueObject.

Generated Code

Here is an example of the code that will be generated when all options and features are active. Note that there are slight differences between a struct and a record struct -most notably IEquatable<ValueObject>.

The comments in the code (normally not generated) serve as a short explanation for the sets of members.

The YourNamespace and YourValueObject symbols are the namespace and value object type names you have chosen. The 'datatype' in this sample is int.

namespace YourNamespace
{
    [System.CodeDom.Compiler.GeneratedCode("Jacobi.ValueObject.Generator", "1.1.0.0")]
    [System.Diagnostics.DebuggerDisplay("Value = {Value}")]
    readonly partial struct YourValueObject : System.IEquatable<YourValueObject>, System.IEquatable<int>, System.IComparable<YourValueObject>, System.IComparable<int>, System.IParsable<ValObj>, System.ISpanParsable<ValObj>
    {
        public YourValueObject() => throw new Jacobi.ValueObject.ValueObjectException("Do not call the default constructor for ValueObject 'YourValueObject'.");
        private readonly int? _value;
        public int Value => _value ?? throw new Jacobi.ValueObject.ValueObjectException("ValueObject 'YourValueObject' was not initialized with a valid value.");
        
        // Constructor (public)
        public YourValueObject(int value) => _value = value;
        
        // Constructor when 'static bool IsValid(int value)' is detected
        public YourValueObject(int value) { if (YourValueObject.IsValid(value)) _value = value; else throw new Jacobi.ValueObject.ValueObjectException($"Validation Failed. The value '{value}' is not valid for Value Object 'YourValueObject'."); }
        public static bool Try(int value, out YourValueObject valueObject) { if (YourValueObject.IsValid(value)) { valueObject = new(value); return true; } valueObject = default; return false; }
        
        // implicit
        public static implicit operator int(YourValueObject value) => value.Value;
        public static implicit operator YourValueObject(int value) => new(value);
        
        // explicit
        public static YourValueObject From(int value) => new(value);
        public override string ToString() => Value.ToString();
        
        // IEquatable<ValueObject> (only for struct)
        public bool Equals(ValObj value) => Value.Equals(value.Value);
        public static bool operator ==(ValObj valueObject, ValObj value) => valueObject.Equals(value);
        public static bool operator !=(ValObj valueObject, ValObj value) => !valueObject.Equals(value);

        // IEquatable<datatype> (implicit)
        public bool Equals(int value) => Value.Equals(value);
        public static bool operator ==(YourValueObject valueObject, int value) => valueObject.Equals(value);
        public static bool operator !=(YourValueObject valueObject, int value) => !valueObject.Equals(value);
        
        // IComparable<ValueObject>
        public int CompareTo(YourValueObject value) => Value.CompareTo(value.Value);
        public static bool operator >(YourValueObject value1, YourValueObject value2) => value1.CompareTo(value2) > 0;
        public static bool operator <(YourValueObject value1, YourValueObject value2) => value1.CompareTo(value2) < 0;
        public static bool operator >=(YourValueObject value1, YourValueObject value2) => value1.CompareTo(value2) >= 0;
        public static bool operator <=(YourValueObject value1, YourValueObject value2) => value1.CompareTo(value2) <= 0;
        
        // IComparable<datatype> (implicit)
        public int CompareTo(int value) => Value.CompareTo(value);
        public static bool operator >(YourValueObject value1, int value2) => value1.CompareTo(value2) > 0;
        public static bool operator <(YourValueObject value1, int value2) => value1.CompareTo(value2) < 0;
        public static bool operator >=(YourValueObject value1, int value2) => value1.CompareTo(value2) >= 0;
        public static bool operator <=(YourValueObject value1, int value2) => value1.CompareTo(value2) <= 0;
        
        // IParsable<ValueObject>
        public static YourValueObject Parse(string? str, System.IFormatProvider? formatProvider) => new(int.Parse(str, formatProvider));
        public static bool TryParse(string? str, System.IFormatProvider? formatProvider, out YourValueObject result)
        {
            if (int.TryParse(str, formatProvider, out var dtResult)) { result = new (dtResult); return true; }
            result = default; return false;
        }
        // ISpanParsable<ValueObject>
        public static YourValueObject Parse(System.ReadOnlySpan<char> str, System.IFormatProvider? formatProvider) => new(int.Parse(str, formatProvider));
        public static bool TryParse(System.ReadOnlySpan<char> str, System.IFormatProvider? formatProvider, out YourValueObject result)
        {
            if (int.TryParse(str, formatProvider, out var dtResult)) { result = new (dtResult); return true; }
            result = default; return false;
        }
    }
}

Unsupported

  • Json Serialization (System.Text.Json or Newtonsoft.Json)
  • AspNet (TypeConvertor)
  • EFcore (ValueConvertor)

For now, you have to write these yourself.

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • .NETStandard 2.0

    • No dependencies.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.3.0 254 11/16/2025
1.2.0 151 11/8/2025
1.1.0 136 11/7/2025
1.0.0 168 11/7/2025