Xpandables.Primitives 10.0.1

There is a newer version of this package available.
See the version list below for details.
dotnet add package Xpandables.Primitives --version 10.0.1
                    
NuGet\Install-Package Xpandables.Primitives -Version 10.0.1
                    
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="Xpandables.Primitives" Version="10.0.1" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Xpandables.Primitives" Version="10.0.1" />
                    
Directory.Packages.props
<PackageReference Include="Xpandables.Primitives" />
                    
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 Xpandables.Primitives --version 10.0.1
                    
#r "nuget: Xpandables.Primitives, 10.0.1"
                    
#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 Xpandables.Primitives@10.0.1
                    
#: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=Xpandables.Primitives&version=10.0.1
                    
Install as a Cake Addin
#tool nuget:?package=Xpandables.Primitives&version=10.0.1
                    
Install as a Cake Tool

System.Primitives

NuGet NuGet Downloads .NET License

Core primitives and utilities for .NET applications. Zero dependencies, foundational abstractions.

Overview

System.Primitives provides foundational abstractions and utilities used throughout the Xpandables.Net ecosystem. It includes strongly-typed primitive wrappers (Value Objects), state management patterns, memory-aware caching, element collections, and essential extension methods.

Built for .NET 10 with zero external dependencies.

Features

Primitives (Value Objects)

  • IPrimitive — Base primitive interface
  • IPrimitive<TValue> — Typed primitive with value
  • IPrimitive<TPrimitive, TValue> — Strongly-typed primitive with factory methods
  • PrimitiveJsonConverterAttribute — JSON serialization support for primitives

Collections

  • ElementCollection — Key-value collection with O(1) lookup
  • ElementEntry — Single entry with key and values
  • ElementCollectionExtensions — Extension methods for collections
  • EnumerableExtensions — LINQ extensions
  • QueryableEmpty<T> — Empty queryable implementation
  • ValidationResultExtensions — Convert validation results to collections
  • HttpHeadersExtensions — Convert HTTP headers to collections

State Pattern

  • IState — State interface
  • IStateContext — State context for state machines
  • IMemento — Memento pattern for state snapshots
  • IOriginator — Originator for memento pattern
  • StateContext — Default state context implementation
  • State — Base state implementation

Caching

  • MemoryAwareCache<TKey, TValue> — Cache with GC pressure monitoring and weak references
  • WeakCacheEntry<T> — Weak reference cache entry
  • ICacheTypeResolver — Type resolver for cached items
  • CacheTypeResolver — Default type resolver

Disposable Helpers

  • Disposable — Base class for IDisposable
  • DisposableAsync — Base class for IAsyncDisposable

Extension Methods

  • StringExtensions — String manipulation and formatting
  • ObjectExtensions — Object null checks and type conversion
  • ExceptionExtensions — Exception details and HTTP status mapping
  • HttpStatusCodeExtensions — HTTP status helpers (Title, Detail, IsSuccess)
  • JsonSerializerExtensions — JSON serialization helpers
  • ThrowExceptionExtensions — Fluent exception throwing

Dependency Injection

  • IAddService — Service registration interface
  • IServiceDecoratorExtensions — Decorator pattern for DI
  • ExportOptions — MEF-style export options
  • StaticConfiguration — Static configuration utilities
  • LazyResolved<T> — Lazy service resolution

Installation

dotnet add package Xpandables.Primitives

Quick Start

Strongly-Typed Primitives

using System;

[PrimitiveJsonConverter<Email, string>]
public readonly record struct Email : IPrimitive<Email, string>
{
    public required string Value { get; init; }

    public static Email Create(string value)
    {
        ArgumentException.ThrowIfNullOrWhiteSpace(value);
        if (!value.Contains('@'))
            throw new ArgumentException("Invalid email format");
        return new Email { Value = value.ToLower() };
    }

    public static string DefaultValue => string.Empty;

    public static bool TryParse(
        string? s, IFormatProvider? provider, out Email result)
    {
        if (s is not null && s.Contains('@'))
        {
            result = Create(s);
            return true;
        }
        result = default;
        return false;
    }

    public string ToString(string? format, IFormatProvider? provider) =>
        Value;

    public int CompareTo(Email other) =>
        string.Compare(Value, other.Value, StringComparison.Ordinal);

    public int CompareTo(object? obj) =>
        obj is Email other ? CompareTo(other) : 1;

    public bool Equals(Email other) => Value == other.Value;
}

// Usage
Email email = Email.Create("john@example.com");
string emailStr = email.Value; // "john@example.com"

Element Collections

using System.Collections;

// Create a collection
var collection = ElementCollection.With("key1", "value1", "value2")
    + new ElementEntry("key2", "value3");

// Access entries
foreach (var entry in collection)
{
    Console.WriteLine($"{entry.Key}: {string.Join(", ", entry.Values)}");
}

// Lookup by key (O(1))
if (collection.TryGetValue("key1", out var values))
{
    Console.WriteLine($"Found: {values}");
}

Memory-Aware Cache

using System.Cache;

// Cleanup every 5 mins, items expire after 1 hour (defaults)
var cache = new MemoryAwareCache<string, User>();

// Get existing or create new
User user = cache.GetOrAdd("user:123", key => LoadUser(key));

// Add or update
cache.AddOrUpdate("user:456", new User { Id = 456, Name = "Jane" });

// Try retrieve
if (cache.TryGetValue("user:123", out var cachedUser))
{
    Console.WriteLine($"Found: {cachedUser.Name}");
}

// Items use weak references — automatically collected under GC pressure

HttpStatusCode Extensions

using System.Net;

var status = HttpStatusCode.BadRequest;

bool isSuccess = status.IsSuccess;            // false
bool isFailure = status.IsFailure;            // true
bool isValidation = status.IsValidationProblem; // true
string title = status.Title;                  // "Bad Request"
string detail = status.Detail;                // Description text

Exception Extensions

try
{
    // Some operation
}
catch (Exception ex)
{
    // Get full message including inner exceptions
    string fullMessage = ex.GetFullExceptionMessage();

    // Convert to ElementCollection for structured error data
    ElementCollection entries = ex.GetElementEntries();

    // Get the appropriate HTTP status code
    HttpStatusCode statusCode = ex.GetHttpStatusCode();
}

🔧 Disposable Helpers

Synchronous Disposable

public class MyResource : Disposable
{
    private readonly Stream _stream;

    public MyResource(Stream stream) => _stream = stream;

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            _stream?.Dispose();
        }
        base.Dispose(disposing);
    }
}

Async Disposable

public class MyAsyncResource : DisposableAsync
{
    private readonly DbConnection _connection;

    public MyAsyncResource(DbConnection connection)
        => _connection = connection;

    protected override async ValueTask DisposeAsync(bool disposing)
    {
        if (disposing)
        {
            await _connection.CloseAsync();
            await _connection.DisposeAsync();
        }
        await base.DisposeAsync(disposing);
    }
}

Core Types

Type Description
IPrimitive<TPrimitive, TValue> Strongly-typed value object
ElementCollection Key-value collection
IStateContext State machine context
MemoryAwareCache<TKey, TValue> Weak-reference cache with auto-cleanup
Disposable / DisposableAsync Disposable base classes

✅ Best Practices

  • Use primitives for domain concepts — Email, Money, ProductId, etc.
  • Validate in Create() method — Fail fast with clear exceptions
  • Make primitives readonly record struct — Stack allocation, value semantics
  • Decorate with PrimitiveJsonConverter — Automatic JSON serialization
  • Keep primitives simple — Single responsibility, no complex business logic
  • Use Disposable/DisposableAsync — Consistent dispose pattern implementation

  • Xpandables.Validation — Specification pattern and validation
  • Xpandables.Optionals — Optional/Maybe monad
  • Xpandables.Results — Result pattern types

📄 License

Apache License 2.0 — Copyright © Kamersoft 2025

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (3)

Showing the top 3 NuGet packages that depend on Xpandables.Primitives:

Package Downloads
Xpandables.Results

Result pattern implementation.

Xpandables.Composition

Composition classes.

Xpandables.Entities.Data

IRepository EntityFramework implementation.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
10.0.2 343 3/15/2026
10.0.1 266 2/20/2026
10.0.0 270 1/9/2026