TrimOrNullify - PawelGerr/Thinktecture.Runtime.Extensions GitHub Wiki

TrimOrNullify

Convenience method for trimming, truncating and nullifying of string.

  • If string is empty or containing whitespace only, then the method returns null.
  • Otherwise the string is trimmed
  • If parameter maxLength is provided then the string will be shortened if necessary.
string value = ...;

var trimmedOrNull = value.TrimOrNullify();

var trimmedAndShortenedOrNull = value.TrimOrNullify(maxLength: 10);

Normalizing a Value Object inside a validation hook

The most common use is to normalize a string member inside ValidateFactoryArguments. Assign the trimmed result back through the hook's ref parameter so the normalized value -- not the raw input -- flows to equality, serialization, and persistence. TrimOrNullify returns null for empty or whitespace-only input, which makes the "reject empty" check a single, allocation-free step:

[ValueObject<string>]
public partial class ProductName
{
    static partial void ValidateFactoryArguments(
        ref ValidationError? validationError,
        ref string value)
    {
        var trimmed = value.TrimOrNullify();

        if (trimmed is null)
        {
            validationError = new ValidationError("Product name cannot be empty.");
            return;
        }

        value = trimmed; // normalized value is what gets stored and compared
    }
}
⚠️ **GitHub.com Fallback** ⚠️