ktsu.SemanticString 1.4.1-pre.3

Prefix Reserved
Suggested Alternatives

ktsu.Semantics.Strings

This is a prerelease version of ktsu.SemanticString.
dotnet add package ktsu.SemanticString --version 1.4.1-pre.3
                    
NuGet\Install-Package ktsu.SemanticString -Version 1.4.1-pre.3
                    
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.SemanticString" Version="1.4.1-pre.3" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="ktsu.SemanticString" Version="1.4.1-pre.3" />
                    
Directory.Packages.props
<PackageReference Include="ktsu.SemanticString" />
                    
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.SemanticString --version 1.4.1-pre.3
                    
#r "nuget: ktsu.SemanticString, 1.4.1-pre.3"
                    
#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.SemanticString@1.4.1-pre.3
                    
#: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.SemanticString&version=1.4.1-pre.3&prerelease
                    
Install as a Cake Addin
#tool nuget:?package=ktsu.SemanticString&version=1.4.1-pre.3&prerelease
                    
Install as a Cake Tool

ktsu.SemanticString

A transparent wrapper for strings providing strong typing, compile-time feedback, and runtime validation

License NuGet NuGet Downloads Build Status GitHub Stars

Introduction

SemanticString provides a transparent wrapper around system strings to give you strong typing, compile time feedback, and runtime validation. It allows you to provide usage context and validation to naked strings in a similar way that Enums do for integers, making your code more type-safe and self-documenting.

Features

  • Strong Typing: Create domain-specific string types to prevent type confusion
  • Compile-time Safety: Catch type mismatches at compile time rather than runtime
  • Runtime Validation: Add custom validation rules to ensure strings meet your requirements
  • Seamless Integration: Works naturally with existing string methods and APIs
  • Zero-overhead: Designed for minimal performance impact when using validated strings

Installation

Package Manager Console

Install-Package ktsu.SemanticString

.NET CLI

dotnet add package ktsu.SemanticString

Package Reference

<PackageReference Include="ktsu.SemanticString" Version="x.y.z" />

Usage Examples

Basic Example

using ktsu.Semantics;

// Create a strong type by deriving a record class from SemanticString<TDerived>:
public record class MyStrongString : SemanticString<MyStrongString> { }

// Use the strong type in your code
public void ProcessData(MyStrongString data)
{
    // Strong typing ensures you can't pass just any string here
    Console.WriteLine(data);
}

// Create an instance
MyStrongString strongString = (MyStrongString)"Hello world";

Type Conversions

public class MyDemoClass
{
    public MyStrongString Stronk { get; set; } = new();

    public static void Demo(MyStrongString inStrongString, string inSystemString, out MyStrongString outStrongString, out string outSystemString)
    {
        // You can implicitly cast down to a System.String
        outSystemString = inStrongString;

        // You must explicitly cast up to a StrongString
        outStrongString = (MyStrongString)inSystemString;

        // You can provide a StrongString to a method that expects a System.String
        Path.Combine(inStrongString, inSystemString);

        // You can use the .WeakString property or .ToString() method to get the underlying System.String
        outSystemString = inStrongString.WeakString;
        outSystemString = inStrongString.ToString();
    }
}

Advanced Usage

Custom Validation

You can provide custom validators which will throw a FormatException at runtime to help you catch data errors:

// Create validator classes by implementing ISemanticStringValidator
public abstract class StartsWithHttp : ISemanticStringValidator
{
    public static bool IsValid(SemanticString? semanticString)
    {
        ArgumentNullException.ThrowIfNull(semanticString);

        return semanticString.StartsWith("http", StringComparison.InvariantCultureIgnoreCase);
    }
}

public abstract class EndsWithDotCom : ISemanticStringValidator
{
    public static bool IsValid(SemanticString? semanticString)
    {
        ArgumentNullException.ThrowIfNull(semanticString);

        return semanticString.EndsWith(".com", StringComparison.InvariantCultureIgnoreCase);
    }
}

// Apply multiple validators to a semantic string type
public record class MyValidatedString : SemanticString<MyValidatedString, StartsWithHttp, EndsWithDotCom> { }

// This will pass validation
MyValidatedString valid = (MyValidatedString)"http://example.com";

// This will throw a FormatException
MyValidatedString invalid = (MyValidatedString)"example.org"; // Throws exception: doesn't end with .com

Complex Validation

For more complex validation scenarios, you can combine multiple validators:

// Email validator
public abstract class EmailValidator : ISemanticStringValidator
{
    public static bool IsValid(SemanticString? semanticString)
    {
        ArgumentNullException.ThrowIfNull(semanticString);
        
        try
        {
            var addr = new System.Net.Mail.MailAddress(semanticString);
            return addr.Address == semanticString;
        }
        catch
        {
            return false;
        }
    }
}

public record class EmailAddress : SemanticString<EmailAddress, EmailValidator> { }

Migration from StrongStrings

SemanticString is the successor to StrongStrings and provides improved functionality while maintaining compatibility with StrongStrings' core features. This section provides guidance for migrating from StrongStrings to SemanticString.

Key Differences and Improvements

  1. Namespace Change: SemanticString uses ktsu.Semantics namespace instead of ktsu.StrongStrings.
  2. Validator Approach: SemanticString supports both:
    • Interface-based validation (ISemanticStringValidator)
    • Attribute-based validation (same as StrongStrings)
  3. Modern Features: SemanticString adds support for ReadOnlySpan<char> and other modern C# features.

Migration Options

Option 1: Direct Replacement

Update your class definitions to use SemanticString instead of StrongString:

// Old (StrongStrings)
using ktsu.StrongStrings;

public record MyString : StrongString<MyString> { }

// New (SemanticString)
using ktsu.Semantics;

public record MyString : SemanticString<MyString> { }
Option 2: Using the Compatibility Layer

The compatibility layer provides aliases to make migration easier:

// Use the aliases namespace for a smooth transition
using ktsu.StrongStrings.Aliases;

// This class is actually using SemanticString under the hood, but with
// StrongString compatible naming
public record MyString : StrongString<MyString> { }

Migrating Attribute Validation

SemanticString fully supports the attribute-based validation pattern from StrongStrings:

// Attribute-based validation works the same way in SemanticString
[StartsWith("http://")]
[EndsWith(".com")]
public record MyUrl : SemanticString<MyUrl> { }

All validation attributes from StrongStrings have been ported:

  • [StartsWith], [EndsWith], [Contains]
  • [RegexMatch], [PrefixAndSuffix]
  • [ValidateAll], [ValidateAny] for logical combinations

Interface-Based Validation

In addition to attribute-based validation, SemanticString also supports interface-based validators:

// Define a validator
public abstract class HttpValidator : ISemanticStringValidator
{
    public static bool IsValid(ISemanticString? semanticString)
    {
        return semanticString?.StartsWith("http", StringComparison.OrdinalIgnoreCase) ?? false;
    }
}

// Use the validator with generics
public record MyUrl : SemanticString<MyUrl, HttpValidator> { }

API Reference

SemanticString<TDerived> Class

Base class for creating semantic string types without validation.

Properties
Name Type Description
WeakString string The underlying string value
Methods
Name Return Type Description
ToString() string Returns the underlying string value
Equals(object?) bool Determines whether the specified object is equal to the current object
GetHashCode() int Returns the hash code for this instance
TryParse(string?, out TDerived?) bool Attempts to parse a string into a SemanticString of type TDerived

SemanticString<TDerived, TValidator1, ...> Class

Base class for creating semantic string types with one or more validators.

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

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

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  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 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.
  • net8.0

    • No dependencies.
  • net9.0

    • No dependencies.

NuGet packages (1)

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

Package Downloads
ktsu.PkmnDB

PkmnDB

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.4.1-pre.3 325 4/27/2025 1.4.1-pre.3 is deprecated because it is no longer maintained.
1.4.1-pre.2 123 4/26/2025
1.4.1-pre.1 177 4/4/2025
1.4.0 1,213 3/30/2025
1.3.5-pre.3 127 2/6/2025
1.3.5-pre.2 119 2/5/2025
1.3.5-pre.1 120 2/5/2025
1.3.4-pre.28 119 2/4/2025
1.3.4-pre.27 120 2/3/2025
1.3.4-pre.26 117 2/1/2025
1.3.4-pre.25 116 1/30/2025
1.3.4-pre.24 123 1/28/2025
1.3.4-pre.23 118 1/26/2025
1.3.4-pre.22 117 1/24/2025
1.3.4-pre.21 117 1/22/2025
1.3.4-pre.20 126 1/20/2025
1.3.4-pre.19 120 1/18/2025
1.3.4-pre.18 112 1/16/2025
1.3.4-pre.17 92 1/14/2025
1.3.4-pre.16 104 1/13/2025
Loading failed

## v1.4.0 (minor)

Changes since v1.3.0:

- Add automation scripts for metadata generation and project management ([@matt-edmondson](https://github.com/matt-edmondson))
- Add LICENSE template ([@matt-edmondson](https://github.com/matt-edmondson))
- Fix analyzer violations ([@matt-edmondson](https://github.com/matt-edmondson))
- Renamed metadata files ([@matt-edmondson](https://github.com/matt-edmondson))

## v1.3.4 (patch)

Changes since v1.3.4-pre.28:

- Add automation scripts for metadata generation and project management ([@matt-edmondson](https://github.com/matt-edmondson))

## v1.3.0 (minor)

Changes since v1.2.18:

- Add new tests for SemanticString and MyValidatedString ([@matt-edmondson](https://github.com/matt-edmondson))
- Add SemanticStringExtensions for string conversions ([@matt-edmondson](https://github.com/matt-edmondson))
- Update binary content of LICENSE.md file ([@matt-edmondson](https://github.com/matt-edmondson))

## v1.2.18 (major)

Changes since 0.0.0.0:

- Initial commit ([@matt-edmondson](https://github.com/matt-edmondson))
- Refactor build scripts ([@matt-edmondson](https://github.com/matt-edmondson))
- Updated README.md ([@matt-edmondson](https://github.com/matt-edmondson))