ktsu.Semantics
1.0.5
Prefix Reserved
See the version list below for details.
dotnet add package ktsu.Semantics --version 1.0.5
NuGet\Install-Package ktsu.Semantics -Version 1.0.5
<PackageReference Include="ktsu.Semantics" Version="1.0.5" />
<PackageVersion Include="ktsu.Semantics" Version="1.0.5" />
<PackageReference Include="ktsu.Semantics" />
paket add ktsu.Semantics --version 1.0.5
#r "nuget: ktsu.Semantics, 1.0.5"
#:package ktsu.Semantics@1.0.5
#addin nuget:?package=ktsu.Semantics&version=1.0.5
#tool nuget:?package=ktsu.Semantics&version=1.0.5
Semantics
A powerful .NET library for creating type-safe, validated string types using semantic meaning. Transform primitive string obsession into strongly-typed, self-validating domain models.
Built with SOLID principles and DRY (Don't Repeat Yourself) practices at its core, the library provides a clean, extensible architecture that promotes maintainable and testable code.
Overview
The Semantics library enables you to create strongly-typed string wrappers that carry semantic meaning and built-in validation. Instead of passing raw strings around your application, you can create specific types like EmailAddress
, FilePath
, or UserId
that are impossible to misuse and automatically validate their content.
Key Features
- Type Safety: Eliminate primitive obsession with strongly-typed string wrappers
- SOLID Architecture: Built following Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, and Dependency Inversion principles
- Extensible Validation: Pluggable validation system with custom strategies and rules
- Factory Pattern: Clean object creation with
ISemanticStringFactory<T>
- Contract Programming: Behavioral contracts ensuring Liskov Substitution Principle compliance
- Automatic Validation: Built-in attribute-based validation system
- Path Handling: Specialized semantic path types with file system operations and polymorphic interface hierarchy
- Quantity Types: Support for numeric values with units and validation
- Performance: Zero-allocation conversions and optimized operations
- Comprehensive: Full XML documentation and IntelliSense support
Quick Start
Installation
dotnet add package ktsu.Semantics
Basic Usage
using ktsu.Semantics;
// Define a custom semantic string type
[IsEmail]
public sealed record EmailAddress : SemanticString<EmailAddress> { }
// Create using factory pattern (recommended)
var factory = new SemanticStringFactory<EmailAddress>();
var email = factory.Create("user@example.com");
// Or use the traditional approach
var email2 = EmailAddress.FromString<EmailAddress>("user@example.com");
// Type safety prevents mixing incompatible string types
public void SendEmail(EmailAddress to, string subject) { /* ... */ }
// This won't compile - type safety in action!
// SendEmail("not-an-email", subject); // Compiler error!
Path Handling
using ktsu.Semantics;
// Use built-in path types with factory pattern
var pathFactory = new SemanticStringFactory<FilePath>();
var filePath = pathFactory.Create(@"C:\temp\data.json");
// Access path properties
Console.WriteLine(filePath.FileName); // data.json
Console.WriteLine(filePath.FileExtension); // .json
Console.WriteLine(filePath.DirectoryPath); // C:\temp
// Traditional approach still works
var absolutePath = AbsolutePath.FromString<AbsolutePath>(@"C:\Projects\MyApp");
Console.WriteLine(absolutePath.Exists); // True/False
Console.WriteLine(absolutePath.IsDirectory); // True/False
// Polymorphic path operations using interfaces
List<IPath> paths = [
AbsoluteFilePath.FromString<AbsoluteFilePath>(@"C:\file.txt"),
RelativeDirectoryPath.FromString<RelativeDirectoryPath>(@"temp\dir"),
FilePath.FromString<FilePath>(@"document.pdf")
];
// Filter by interface type
var filePaths = paths.OfType<IFilePath>().ToList();
var absolutePaths = paths.OfType<IAbsolutePath>().ToList();
// Polymorphic method parameters
public void ProcessAnyPath(IPath path) { /* works with any path type */ }
public void ProcessFileOnly(IFilePath filePath) { /* files only */ }
Multiple Validations
// Combine multiple validation attributes
[IsNotEmpty, IsEmail, HasLength(5, 100)]
public sealed record ProfessionalEmail : SemanticString<ProfessionalEmail> { }
// Use validation strategies for complex scenarios
[ValidateAny]
[IsEmail, IsUrl]
public sealed record ContactInfo : SemanticString<ContactInfo> { }
var factory = new SemanticStringFactory<ContactInfo>();
var email = factory.Create("user@example.com"); // ✅ Valid (email)
var url = factory.Create("https://example.com"); // ✅ Valid (URL)
Documentation
Comprehensive documentation is available in the docs/
directory:
- Architecture Guide - Detailed overview of SOLID principles, design patterns, and system architecture
- Advanced Usage Guide - Advanced features including custom validation strategies, dependency injection, and best practices
- Validation Reference - Complete reference of all built-in validation attributes and strategies
Examples
Extensive examples demonstrating all library features are available in the examples/
directory. Start with the Examples Index for organized learning paths:
- Getting Started - Basic usage patterns and your first semantic strings
- Validation Attributes - Built-in validation and custom rules
- Path Handling - File system paths and validation
- Factory Pattern - Object creation and dependency injection
- Real-World Scenarios - Complete domain examples for e-commerce, finance, and more
Each example includes complete, runnable code that you can copy and adapt to your specific needs.
Common Use Cases
Domain-Specific Types
// Create strongly-typed identifiers
[HasLength(8, 12), IsNotEmpty]
public sealed record UserId : SemanticString<UserId> { }
[HasLength(3, 10), IsNotEmpty]
public sealed record ProductSku : SemanticString<ProductSku> { }
// Use them in your domain models
public class Order
{
public UserId CustomerId { get; set; }
public ProductSku[] Items { get; set; }
}
Input Validation
public class UserController : ControllerBase
{
private readonly ISemanticStringFactory<EmailAddress> _emailFactory;
public UserController(ISemanticStringFactory<EmailAddress> emailFactory)
{
_emailFactory = emailFactory;
}
[HttpPost]
public IActionResult CreateUser([FromBody] CreateUserRequest request)
{
if (!_emailFactory.TryCreate(request.Email, out var emailAddress))
{
return BadRequest("Invalid email format");
}
// emailAddress is guaranteed to be valid
var user = new User(emailAddress);
return Ok(user);
}
}
File System Operations
// Work with type-safe paths
var sourceFactory = new SemanticStringFactory<FilePath>();
var destinationFactory = new SemanticStringFactory<DirectoryPath>();
var sourceFile = sourceFactory.Create(@"C:\temp\data.csv");
var destinationDir = destinationFactory.Create(@"C:\backup\");
if (sourceFile.Exists)
{
// Type-safe file operations
File.Copy(sourceFile, Path.Combine(destinationDir, sourceFile.FileName));
}
Built-in Validation Attributes
The library includes comprehensive validation for common scenarios:
- String:
IsEmail
,IsUrl
,IsNotEmpty
,HasLength
- Path:
IsPath
,IsAbsolutePath
,IsRelativePath
,IsFilePath
,IsDirectoryPath
,DoesExist
- Numeric:
IsPositive
,IsNegative
,IsInRange
See the Validation Reference for complete details.
Dependency Injection
// Register in your DI container
services.AddTransient<ISemanticStringFactory<EmailAddress>, SemanticStringFactory<EmailAddress>>();
services.AddTransient<ISemanticStringFactory<UserId>, SemanticStringFactory<UserId>>();
// Inject into services
public class UserService
{
private readonly ISemanticStringFactory<EmailAddress> _emailFactory;
public UserService(ISemanticStringFactory<EmailAddress> emailFactory)
{
_emailFactory = emailFactory;
}
}
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
- 📖 Documentation
- 🐛 Issues
- 💬 Discussions
- 📦 NuGet Package
Product | Versions 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. |
-
net9.0
- FluentValidation (>= 12.0.0)
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 | 168 | 8/16/2025 | |
1.0.20-pre.1 | 486 | 7/22/2025 | |
1.0.19 | 302 | 6/18/2025 | |
1.0.18 | 181 | 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 | 292 | 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 | 207 | 6/8/2025 | |
1.0.3 | 206 | 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.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))