Noundry.Guardian 1.0.0

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

Noundry.Guardian

NuGet License: MIT .NET

Noundry.Guardian is a lightweight, high-performance library providing guard clauses for validating method parameters and ensuring defensive programming practices in .NET applications.

Features

  • Comprehensive Validation: Guards against null, empty, default values, out-of-range values, and invalid formats
  • Type-Safe: Full support for generics and nullable reference types
  • Performance Optimized: Minimal overhead with inline methods and zero allocations for successful validations
  • Developer Friendly: Intuitive API with IntelliSense support and detailed XML documentation
  • Framework Support: Targets .NET 6.0, 7.0, 8.0, 9.0, 10.0, and .NET Standard 2.0/2.1
  • Modern C# Features: Uses CallerArgumentExpression for automatic parameter name capture

Installation

Install Guardian via NuGet:

dotnet add package Noundry.Guardian

Or via Package Manager Console:

Install-Package Noundry.Guardian

Quick Start

using Noundry.Guardian;

public class Product
{
    public string Name { get; }
    public decimal Price { get; }
    public int StockQuantity { get; }

    public Product(string name, decimal price, int stockQuantity)
    {
        Name = Guard.Against.NullOrWhiteSpace(name);
        Price = Guard.Against.NegativeOrZero(price);
        StockQuantity = Guard.Against.Negative(stockQuantity);
    }
}

Available Guard Clauses

Null Checks

  • Null<T>() - Throws if value is null
  • NullOrEmpty() - Throws if string/collection is null or empty
  • NullOrWhiteSpace() - Throws if string is null, empty, or whitespace

Default Value Checks

  • Default<T>() - Throws if reference type value is null/default
  • DefaultStruct<T>() - Throws if struct value equals default(T) (use for Guid, DateTime, etc.)

Numeric Range Checks

  • Negative() - Throws if value is negative
  • Zero() - Throws if value is zero
  • NegativeOrZero() - Throws if value is negative or zero
  • Positive() - Throws if value is positive
  • OutOfRange() - Throws if value is outside specified range
  • GreaterThan() - Throws if value is greater than maximum
  • GreaterThanOrEqualTo() - Throws if value is greater than or equal to maximum
  • LessThan() - Throws if value is less than minimum
  • LessThanOrEqualTo() - Throws if value is less than or equal to minimum

String Validation

  • InvalidFormat() - Throws if string doesn't match regex pattern
  • InvalidLength() - Throws if string length is outside specified range

Enum Validation

  • NotInEnum() - Throws if value is not a defined enum value

Collection Validation

  • NullOrEmpty() - Throws if collection is null or empty

Custom Validation

  • Condition() - Throws if condition is false
  • NotOneOf() - Throws if value is not in allowed values list

Usage Examples

Basic Parameter Validation

public void ProcessOrder(Guid orderId, string customerEmail, decimal amount)
{
    Guard.Against.DefaultStruct(orderId);
    Guard.Against.InvalidFormat(customerEmail, @"^[^@\s]+@[^@\s]+\.[^@\s]+$");
    Guard.Against.OutOfRange(amount, 0.01m, 10000m);

    // Process the order...
}

Constructor Validation

public class Customer
{
    public Guid Id { get; }
    public string Name { get; }
    public int Age { get; }
    public string Email { get; }

    public Customer(Guid id, string name, int age, string email)
    {
        Id = Guard.Against.DefaultStruct(id);
        Name = Guard.Against.NullOrWhiteSpace(name);
        Name = Guard.Against.InvalidLength(Name, 2, 100);
        Age = Guard.Against.OutOfRange(age, 18, 120);
        Email = Guard.Against.InvalidFormat(email, @"^[^@\s]+@[^@\s]+\.[^@\s]+$");
    }
}

Custom Business Rules

public void TransferFunds(decimal amount, Account fromAccount, Account toAccount)
{
    Guard.Against.NegativeOrZero(amount);
    Guard.Against.Null(fromAccount);
    Guard.Against.Null(toAccount);
    Guard.Against.Condition(
        fromAccount.Balance >= amount,
        nameof(amount),
        $"Insufficient funds. Available: {fromAccount.Balance}, Requested: {amount}"
    );
    
    // Perform transfer...
}

Enum Validation

public enum OrderStatus
{
    Pending,
    Processing,
    Shipped,
    Delivered,
    Cancelled
}

public void UpdateOrderStatus(OrderStatus status)
{
    Guard.Against.NotInEnum(status);
    
    // Update status...
}

Collection Validation

public void ProcessItems(List<Item> items)
{
    Guard.Against.NullOrEmpty(items);
    
    foreach (var item in items)
    {
        Guard.Against.Null(item);
        // Process item...
    }
}

Method Chaining

public class Product
{
    private string _name;
    private decimal _price;

    public void Update(string name, decimal price)
    {
        _name = Guard.Against.NullOrWhiteSpace(name);
        _name = Guard.Against.InvalidLength(_name, 3, 50);
        
        _price = Guard.Against.NegativeOrZero(price);
        _price = Guard.Against.GreaterThan(_price, 99999.99m);
    }
}

Custom Error Messages

public void SetDiscount(decimal discountPercentage)
{
    Guard.Against.OutOfRange(
        discountPercentage, 
        0, 
        100,
        message: "Discount percentage must be between 0 and 100"
    );
    
    // Apply discount...
}

Performance Considerations

Guardian is designed for minimal performance impact:

  • All guard methods are optimized for the success path
  • No allocations when validation passes
  • Inline method hints for better JIT optimization
  • Generic constraints prevent boxing of value types

Best Practices

  1. Use at Method Entry Points: Place guards at the beginning of methods to fail fast
  2. Be Specific: Use the most specific guard clause for better error messages
  3. Custom Messages: Provide custom messages for domain-specific validations
  4. Combine Guards: Use multiple guards for comprehensive validation
  5. Consistent Usage: Apply guards consistently across your codebase

Error Handling

Guardian throws appropriate exceptions based on the validation type:

  • ArgumentNullException - For null values
  • ArgumentException - For invalid values, formats, or conditions
  • ArgumentOutOfRangeException - For values outside acceptable ranges

License

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

Acknowledgments

Noundry.Guardian is inspired by popular guard clause libraries and defensive programming practices in the .NET ecosystem.

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  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 is compatible.  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. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 is compatible. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • .NETStandard 2.0

  • .NETStandard 2.1

    • No dependencies.
  • net10.0

    • No dependencies.
  • net8.0

    • No dependencies.
  • net9.0

    • No dependencies.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.0 126 3/4/2026