ktsu.Semantics 1.0.12

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.12
                    
NuGet\Install-Package ktsu.Semantics -Version 1.0.12
                    
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.12" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="ktsu.Semantics" Version="1.0.12" />
                    
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.12
                    
#r "nuget: ktsu.Semantics, 1.0.12"
                    
#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.12
                    
#: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.12
                    
Install as a Cake Addin
#tool nuget:?package=ktsu.Semantics&version=1.0.12
                    
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-pre.1 477 7/22/2025
1.0.19 217 6/18/2025
1.0.18 172 6/16/2025
1.0.17 142 6/16/2025
1.0.17-pre.1 113 6/16/2025
1.0.16 136 6/16/2025
1.0.15 133 6/16/2025
1.0.14 124 6/15/2025
1.0.13 257 6/13/2025
1.0.12 257 6/13/2025
1.0.11 280 6/12/2025
1.0.10 284 6/12/2025
1.0.9 281 6/12/2025
1.0.8 282 6/12/2025
1.0.7 283 6/11/2025
1.0.6 282 6/10/2025
1.0.5 278 6/10/2025
1.0.4 196 6/8/2025
1.0.3 194 6/8/2025
1.0.2 194 6/8/2025
1.0.1 190 6/8/2025
1.0.0 199 6/8/2025
1.0.0-pre.1 88 6/7/2025

## v1.0.12 (patch)

Changes since v1.0.11:

- Enhance the Semantics library by implementing key physical relationships across various domains, including Mechanics, Electrical, Thermal, and Optical. Introduce operator overloads for quantities such as Force, Mass, Energy, ElectricCharge, and LuminousFlux, enabling intuitive calculations. Ensure all new implementations adhere to coding standards and include comprehensive XML documentation. This update significantly improves the usability and functionality of the library, providing a robust framework for physical quantity calculations in .NET applications. ([@matt-edmondson](https://github.com/matt-edmondson))
- Implement additional physical relationships in the Semantics library, enhancing the Acoustic, Electrical, and Mechanical domains. Introduce operator overloads for calculating sound power from intensity and area, charge from capacitance and voltage, and torque from force and distance. Update existing quantities to support intuitive calculations, ensuring adherence to coding standards and comprehensive XML documentation. This update further solidifies the library's framework for physical quantity calculations in .NET applications. ([@matt-edmondson](https://github.com/matt-edmondson))
- Refactor operator overloads in the Semantics library to resolve ambiguities between work/energy and torque calculations. Update the Force and Length operators, replacing the removed method with an explicit CalculateTorque method. Enhance documentation and ensure compliance with coding standards. This update improves clarity and usability for physical quantity calculations in .NET applications. ([@matt-edmondson](https://github.com/matt-edmondson))
- Implement the Chemical Domain in the Semantics library, completing 10 quantities: ActivationEnergy, AmountOfSubstance, Concentration, DynamicViscosity, EnzymeActivity, MolarMass, PH, RateConstant, ReactionRate, and SurfaceTension. Introduce PhysicalConstants.cs for centralized management of physical constants, ensuring accuracy and maintainability. Update PhysicalDimensions and Units to incorporate new chemical dimensions and units. Achieve 376 passing tests, marking the Chemical domain as fully implemented in TODO_DOMAINS.md. ([@matt-edmondson](https://github.com/matt-edmondson))
- Implement additional physical relationships in the Semantics library, focusing on the Acoustic, Chemical, and Fluid Dynamics domains. Introduce operator overloads for calculating acoustic impedance from density and sound speed, photon energy from frequency, and apply the ideal gas law for amount of substance calculations. Update existing quantities to enhance usability and ensure adherence to coding standards with comprehensive XML documentation. This update further strengthens the library's framework for physical quantity calculations in .NET applications. ([@matt-edmondson](https://github.com/matt-edmondson))
- Refactor physics relationship calculations in the Semantics library to resolve operator ambiguities and enhance clarity. Update the Force and Length operators to distinguish between work/energy and torque calculations, introducing explicit methods for torque. Clean up unused variables and improve documentation for better usability. This update strengthens the library's framework for accurate physical quantity calculations in .NET applications. ([@matt-edmondson](https://github.com/matt-edmondson))
- Complete the Fluid Dynamics domain in the Semantics library by implementing key quantities including KinematicViscosity, BulkModulus, VolumetricFlowRate, MassFlowRate, and ReynoldsNumber. Update the tracker to reflect the successful implementation of all 8 domains, achieving a total of 85 quantities. Ensure all new quantities adhere to coding standards and include comprehensive XML documentation. This marks a significant milestone in the library's development, providing a robust and professional-grade physical quantities system for .NET applications. ([@matt-edmondson](https://github.com/matt-edmondson))
- Implement the Mechanical Domain in the Semantics library, introducing quantities such as Force, Energy, Pressure, and their associated calculations. Centralize physical constants management in PhysicalConstants.cs, ensuring type-safe access to constants like standard gravity and atmospheric pressure. Update PhysicalDimensions and Units to incorporate new mechanical dimensions and units. Achieve comprehensive testing with 100% passing tests, marking the Mechanical domain as fully implemented in the updated implementation plan and progress tracker. ([@matt-edmondson](https://github.com/matt-edmondson))
- Enhance the Semantics library by implementing the Optical, Nuclear, and Fluid Dynamics domains. Introduce new quantities such as Illuminance, Luminance, RefractiveIndex, AbsorbedDose, EquivalentDose, and various fluid dynamics properties including BulkModulus and KinematicViscosity. Centralize physical constants in PhysicalConstants.cs for type-safe access. Update PhysicalDimensions and Units to reflect new dimensions and units. Achieve comprehensive testing with all new quantities passing, marking significant progress in the implementation plan. ([@matt-edmondson](https://github.com/matt-edmondson))
## v1.0.11 (patch)

Changes since v1.0.10:

- Implement comprehensive chemical quantities including ActivationEnergy, AmountOfSubstance, Concentration, DynamicViscosity, EnzymeActivity, MolarMass, pH, RateConstant, ReactionRate, and SurfaceTension. Update PhysicalDimensions and Units to include new chemical dimensions and units, enhancing the completeness of the quantities implementation. ([@matt-edmondson](https://github.com/matt-edmondson))
- Implement chemical quantities including ActivationEnergy, AmountOfSubstance, Concentration, DynamicViscosity, EnzymeActivity, MolarMass, PH, RateConstant, ReactionRate, and SurfaceTension. Update PhysicalDimensions and Units to include new chemical dimensions and units. Mark the Chemical domain as fully implemented in TODO_DOMAINS.md, enhancing the completeness of the quantities implementation. ([@matt-edmondson](https://github.com/matt-edmondson))
## v1.0.10 (patch)

Changes since v1.0.9:

- Implement comprehensive acoustic quantities including SoundPressureLevel, SoundIntensityLevel, SoundPowerLevel, ReflectionCoefficient, NoiseReductionCoefficient, SoundTransmissionClass, Loudness, Pitch, Sharpness, Sensitivity, and DirectionalityIndex. Update PhysicalDimensions to include new acoustic dimensions and mark the Acoustic domain as fully implemented in TODO_DOMAINS.md, enhancing the completeness of the quantities implementation. ([@matt-edmondson](https://github.com/matt-edmondson))
- Implement thermal quantities including Heat, HeatCapacity, SpecificHeat, ThermalConductivity, ThermalExpansion, ThermalDiffusivity, HeatTransferCoefficient, and Entropy. Update TODO_DOMAINS.md to mark the Thermal domain as fully implemented, enhancing the completeness of the quantities implementation. ([@matt-edmondson](https://github.com/matt-edmondson))
## v1.0.9 (patch)

Changes since v1.0.8:

- Implement core acoustic quantities including Frequency, Wavelength, SoundPressure, SoundIntensity, SoundPower, AcousticImpedance, SoundSpeed, SoundAbsorption, and ReverberationTime. Update PhysicalDimensions to include new acoustic dimensions and mark the Acoustic domain as significantly progressed in TODO_DOMAINS.md, enhancing the completeness of the quantities implementation. ([@matt-edmondson](https://github.com/matt-edmondson))
## v1.0.8 (patch)

Changes since v1.0.7:

- Refactor conversions ([@matt-edmondson](https://github.com/matt-edmondson))
- Refactor PhysicalQuantity and PhysicalDimension relationship by moving BaseUnit property to PhysicalDimension. Update related classes to access BaseUnit through Dimension, enhancing clarity and encapsulation of dimensional properties. ([@matt-edmondson](https://github.com/matt-edmondson))
- Implement comprehensive quantities for Mechanics and Electrical domains, including new classes for AngularAcceleration, AngularVelocity, Density, ElectricConductivity, ElectricField, and others. Update PhysicalDimensions to include new dimensions and mark all quantities as implemented in TODO_DOMAINS.md, enhancing the overall structure and completeness of the quantities implementation. ([@matt-edmondson](https://github.com/matt-edmondson))
- Refactor conversions ([@matt-edmondson](https://github.com/matt-edmondson))
- Refactor conversions ([@matt-edmondson](https://github.com/matt-edmondson))
- Enhance PhysicalDimension constructor to require IUnit parameter, ensuring proper initialization in operator overloads. Update PhysicalDimensions to reflect new constructor signature, improving clarity and preventing type conversion errors. ([@matt-edmondson](https://github.com/matt-edmondson))
- Refactor PhysicalDimension to accept BaseUnit in constructor, removing runtime lookup. Update PhysicalDimensions to initialize dimensions with their respective base units, enhancing performance and clarity in dimensional properties. ([@matt-edmondson](https://github.com/matt-edmondson))
- Refactor conversions ([@matt-edmondson](https://github.com/matt-edmondson))
- Organize quantities ([@matt-edmondson](https://github.com/matt-edmondson))
- Refactor quantities ([@matt-edmondson](https://github.com/matt-edmondson))
- Refactor quantities ([@matt-edmondson](https://github.com/matt-edmondson))
- Refactor quantities ([@matt-edmondson](https://github.com/matt-edmondson))
- Add tests ([@matt-edmondson](https://github.com/matt-edmondson))
- Add tests ([@matt-edmondson](https://github.com/matt-edmondson))
## 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))