ktsu.Semantics 1.0.7

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

ktsu.Semantics

NuGet Version NuGet Downloads Build Status

A powerful .NET library for creating type-safe, validated types with semantic meaning. Transform primitive string obsession into strongly-typed, self-validating domain models with comprehensive validation, specialized path handling, and quantity types.

Overview

The Semantics library enables you to create strongly-typed wrappers that carry semantic meaning and built-in validation. Instead of passing raw primitives around your application, you can create specific types like EmailAddress, FilePath, Temperature, or UserId that are impossible to misuse and automatically validate their content.

🌟 Key Features

  • Type Safety: Eliminate primitive obsession with strongly-typed wrappers
  • Comprehensive Validation: 50+ built-in validation attributes for all common scenarios
  • Path Handling: Specialized path types with polymorphic interfaces and file system operations
  • Quantity System: Type-safe numeric values with units and arithmetic operations
  • Factory Pattern: Clean object creation with dependency injection support
  • Performance Optimized: Span-based operations, pooled builders, and minimal allocations
  • Enterprise Ready: Full .NET ecosystem integration (ASP.NET Core, Entity Framework, etc.)

🚀 Quick Start

Installation

dotnet add package ktsu.Semantics

Basic Usage

using ktsu.Semantics;

// Define strongly-typed domain models
[IsEmail]
public sealed record EmailAddress : SemanticString<EmailAddress> { }

[HasLength(8, 50), IsNotEmpty]
public sealed record UserId : SemanticString<UserId> { }

// Simple direct usage - Clean API with type inference:

// 1. Create methods (recommended) - no generic parameters needed!
var email1 = EmailAddress.Create("user@example.com");
var userId1 = UserId.Create("USER_12345");

// 2. From character arrays
char[] emailChars = ['u', 's', 'e', 'r', '@', 'e', 'x', 'a', 'm', 'p', 'l', 'e', '.', 'c', 'o', 'm'];
var email2 = EmailAddress.Create(emailChars);

// 3. From ReadOnlySpan<char> (performance optimized)
var userId2 = UserId.Create("USER_12345".AsSpan());

// 4. Explicit string casting
var email3 = (EmailAddress)"user@example.com";
var userId3 = (UserId)"USER_12345";

// 5. Safe creation with TryCreate (no exceptions)
if (EmailAddress.TryCreate("maybe@invalid", out EmailAddress? safeEmail))
{
    // Use safeEmail - validation succeeded
}

// Compile-time safety prevents mistakes
public void SendWelcomeEmail(EmailAddress to, UserId userId) { /* ... */ }

// This won't compile - type safety in action!
// SendWelcomeEmail(userId, email); // ❌ Compiler error!

Factory Pattern Usage

// Use factory pattern (recommended for dependency injection)
var emailFactory = new SemanticStringFactory<EmailAddress>();
var userFactory = new SemanticStringFactory<UserId>();

// Clean overloaded API - Create methods
var email = emailFactory.Create("user@example.com");
var userId = userFactory.Create("USER_12345");

// All input types supported via overloading
var email2 = emailFactory.Create(['u', 's', 'e', 'r', '@', 'e', 'x', 'a', 'm', 'p', 'l', 'e', '.', 'c', 'o', 'm']);
var userId2 = userFactory.Create("USER_12345".AsSpan());

// Safe creation with TryCreate
if (emailFactory.TryCreate("maybe@invalid", out EmailAddress? safeEmail))
{
    // Success!
}

// Legacy FromString methods still available  
var email3 = emailFactory.FromString("user@example.com");

Semantic Quantities

// Define quantity types with units
public sealed record Temperature : SemanticQuantity<Temperature, decimal> { }
public sealed record Distance : SemanticQuantity<Distance, double> { }

// Create instances
var temp1 = Temperature.Create(23.5m);  // 23.5°C
var temp2 = Temperature.Create(18.2m);  // 18.2°C

// Type-safe arithmetic operations
var avgTemp = (temp1 + temp2) / 2m;     // Average temperature
var tempDiff = temp1 - temp2;           // Temperature difference

// Quantities are strongly typed
public void SetThermostat(Temperature target) { /* ... */ }

// This won't compile - different quantity types
// SetThermostat(Distance.Create(100)); // ❌ Compiler error!

Path Handling

// Use specialized path types
var fileFactory = new SemanticStringFactory<AbsoluteFilePath>();
var configFile = fileFactory.Create(@"C:\app\config.json");

// Rich path operations
Console.WriteLine(configFile.FileName);        // config.json
Console.WriteLine(configFile.FileExtension);   // .json  
Console.WriteLine(configFile.DirectoryPath);   // C:\app
Console.WriteLine(configFile.Exists);          // True/False

// Polymorphic path collections
List<IPath> allPaths = [
    AbsoluteFilePath.FromString<AbsoluteFilePath>(@"C:\data.txt"),
    RelativeDirectoryPath.FromString<RelativeDirectoryPath>(@"logs\app"),
    FilePath.FromString<FilePath>(@"document.pdf")
];

// Filter by interface type
var filePaths = allPaths.OfType<IFilePath>().ToList();
var absolutePaths = allPaths.OfType<IAbsolutePath>().ToList();

Complex Validation

// Combine multiple validation rules
[IsNotEmpty, IsEmail, HasLength(5, 100)]
public sealed record BusinessEmail : SemanticString<BusinessEmail> { }

// Use validation strategies for flexible requirements
[ValidateAny] // Either email OR phone is acceptable
[IsEmail, RegexMatch(@"^\+?\d{10,15}$")]
public sealed record ContactInfo : SemanticString<ContactInfo> { }

// First-class type validation
[IsDateTime]
public sealed record ScheduledDate : SemanticString<ScheduledDate> { }

[IsDecimal, IsPositive]
public sealed record Price : SemanticString<Price> { }

[IsGuid]
public sealed record TransactionId : SemanticString<TransactionId> { }

🔧 Common Use Cases

E-commerce Domain

[HasLength(3, 20), IsNotEmpty]
public sealed record ProductSku : SemanticString<ProductSku> { }

[IsPositive, IsDecimal]  
public sealed record Price : SemanticString<Price> { }

[IsEmail]
public sealed record CustomerEmail : SemanticString<CustomerEmail> { }

public class Order
{
    public CustomerEmail CustomerEmail { get; set; }
    public ProductSku[] Items { get; set; }
    public Price TotalAmount { get; set; }
}

Configuration Management

[IsAbsolutePath, DoesExist]
public sealed record ConfigFilePath : SemanticString<ConfigFilePath> { }

[IsIpAddress]
public sealed record ServerAddress : SemanticString<ServerAddress> { }

[IsInRange(1, 65535)]
public sealed record Port : SemanticQuantity<Port, int> { }

Scientific Computing

public sealed record Temperature : SemanticQuantity<Temperature, double> { }
public sealed record Pressure : SemanticQuantity<Pressure, decimal> { }

// Type-safe calculations
public Volume CalculateVolume(Pressure pressure, Temperature temperature)
{
    // Ideal gas law calculation with type safety
    var result = (pressure * Volume.Create(1.0)) / temperature;
    return result;
}

🏗️ Dependency Injection

// Register factories in your DI container
services.AddTransient<ISemanticStringFactory<EmailAddress>, SemanticStringFactory<EmailAddress>>();

// Use in services
public class UserService
{
    private readonly ISemanticStringFactory<EmailAddress> _emailFactory;

    public UserService(ISemanticStringFactory<EmailAddress> emailFactory)
    {
        _emailFactory = emailFactory;
    }

    public async Task<User> CreateUserAsync(string email)
    {
        // Factory handles validation and throws meaningful exceptions
        var validatedEmail = _emailFactory.Create(email);
        return new User(validatedEmail);
    }
}

📖 Documentation

Comprehensive documentation is available in the docs/ directory:

💡 Examples

Extensive examples are available in docs/examples/:

🤝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.

📄 License

This project is licensed under the MIT License - see the LICENSE.md file for details.

🆘 Support


Transform your primitive-obsessed code into a strongly-typed, self-validating domain model with ktsu.Semantics.

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

NuGet packages (1)

Showing the top 1 NuGet packages that depend on ktsu.Semantics:

Package Downloads
ktsu.AppData

Application data storage library for .NET that provides type-safe persistence with dependency injection support. Features automatic backup and recovery, debounced saves, mock file system support for testing, and cross-platform storage using the user's app data directory.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.20 171 8/16/2025 1.0.20 is deprecated because it is no longer maintained.
1.0.20-pre.1 506 7/22/2025
1.0.19 313 6/18/2025
1.0.18 183 6/16/2025
1.0.17 149 6/16/2025
1.0.17-pre.1 122 6/16/2025
1.0.16 144 6/16/2025
1.0.15 142 6/16/2025
1.0.14 134 6/15/2025
1.0.13 266 6/13/2025
1.0.12 265 6/13/2025
1.0.11 288 6/12/2025
1.0.10 293 6/12/2025
1.0.9 292 6/12/2025
1.0.8 290 6/12/2025
1.0.7 296 6/11/2025
1.0.6 291 6/10/2025
1.0.5 286 6/10/2025
1.0.4 209 6/8/2025
1.0.3 207 6/8/2025
1.0.2 204 6/8/2025
1.0.1 198 6/8/2025
1.0.0 213 6/8/2025
1.0.0-pre.1 96 6/7/2025

## v1.0.7 (patch)

Changes since v1.0.6:

- Update README and documentation to provide a comprehensive overview of the ktsu.Semantics library ([@matt-edmondson](https://github.com/matt-edmondson))
- Add more physical quantities ([@matt-edmondson](https://github.com/matt-edmondson))
## v1.0.6 (patch)

Changes since v1.0.5:

- Update README and architecture documentation for examples directory structure ([@matt-edmondson](https://github.com/matt-edmondson))
## v1.0.5 (patch)

Changes since v1.0.4:

- Refactor semantic validation attributes and introduce new path validation strategies ([@matt-edmondson](https://github.com/matt-edmondson))
- Refactor validation attributes and enhance documentation ([@matt-edmondson](https://github.com/matt-edmondson))
- Implement semantic path operators and enhance path interfaces ([@matt-edmondson](https://github.com/matt-edmondson))
- Refactor casing validation attributes to utilize FluentValidation ([@matt-edmondson](https://github.com/matt-edmondson))
-  Add new semantic path types and validation strategies ([@matt-edmondson](https://github.com/matt-edmondson))
- Add more teats ([@matt-edmondson](https://github.com/matt-edmondson))
- Integrate FluentValidation into semantic validation attributes ([@matt-edmondson](https://github.com/matt-edmondson))
- Enhance documentation and suppress CA1812 warning ([@matt-edmondson](https://github.com/matt-edmondson))
- Refactor validation attributes to utilize FluentValidation ([@matt-edmondson](https://github.com/matt-edmondson))
## v1.0.4 (patch)

Changes since v1.0.3:

- Enhance semantic path documentation and interface functionality ([@matt-edmondson](https://github.com/matt-edmondson))
## v1.0.3 (patch)

Changes since v1.0.2:

- Refactor GitHub Actions workflow to reposition .NET SDK setup step for improved clarity and maintainability. The setup step is now placed after the JDK setup, ensuring a more logical flow in the CI process. ([@matt-edmondson](https://github.com/matt-edmondson))
## v1.0.2 (patch)

Changes since v1.0.1:

- Enhance documentation for path interface hierarchy and examples ([@matt-edmondson](https://github.com/matt-edmondson))
- Add interfaces for path type hierarchy to enable polymorphism ([@matt-edmondson](https://github.com/matt-edmondson))
- Add comprehensive interface tests for semantic path types ([@matt-edmondson](https://github.com/matt-edmondson))
## v1.0.1 (patch)

Changes since v1.0.0:

- Enhance GitHub Actions workflow by adding .NET SDK setup step with caching for improved build performance. ([@matt-edmondson](https://github.com/matt-edmondson))
## v1.0.0 (patch)

Changes since v1.0.0-pre.1:

- Remove DebugConsole project and associated test files ([@matt-edmondson](https://github.com/matt-edmondson))
- Add DebugConsole project and initial tests for SemanticString functionality ([@matt-edmondson](https://github.com/matt-edmondson))
## v1.0.0-pre.1 (prerelease)

- initial version ([@matt-edmondson](https://github.com/matt-edmondson))