Noundry.Guardian 1.0.0
by George Rios
Guardian
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, 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 nullNullOrEmpty()
- Throws if string/collection is null or emptyNullOrWhiteSpace()
- Throws if string is null, empty, or whitespace
Default Value Checks
Default<T>()
- Throws if value equals default(T)
Numeric Range Checks
Negative()
- Throws if value is negativeZero()
- Throws if value is zeroNegativeOrZero()
- Throws if value is negative or zeroPositive()
- Throws if value is positiveOutOfRange()
- Throws if value is outside specified rangeGreaterThan()
- Throws if value is greater than maximumGreaterThanOrEqualTo()
- Throws if value is greater than or equal to maximumLessThan()
- Throws if value is less than minimumLessThanOrEqualTo()
- Throws if value is less than or equal to minimum
String Validation
InvalidFormat()
- Throws if string doesn't match regex patternInvalidLength()
- 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 falseNotOneOf()
- 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.Default(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.Default(id);
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
- Use at Method Entry Points: Place guards at the beginning of methods to fail fast
- Be Specific: Use the most specific guard clause for better error messages
- Custom Messages: Provide custom messages for domain-specific validations
- Combine Guards: Use multiple guards for comprehensive validation
- Consistent Usage: Apply guards consistently across your codebase
Error Handling
Guardian throws appropriate exceptions based on the validation type:
ArgumentNullException
- For null valuesArgumentException
- For invalid values, formats, or conditionsArgumentOutOfRangeException
- For values outside acceptable ranges
Contributing
Contributions are welcome! Please read our Contributing Guide for details on our code of conduct and the process for submitting pull requests.
License
This project is licensed under the MIT License - see the LICENSE file for details.
Support
- Issues: GitHub Issues
- Discussions: GitHub Discussions
- Documentation: Wiki
Acknowledgments
Guardian is inspired by popular guard clause libraries and defensive programming practices in the .NET ecosystem.
.NET 6.0
No dependencies.
.NET 7.0
No dependencies.
.NET 8.0
No dependencies.
.NET Standard 2.0
- System.Memory (>= 4.5.5)
.NET Standard 2.1
No dependencies.
No packages depend on Noundry.Guardian.
Version | Downloads | Last Updated |
---|---|---|
1.0.0 Current | 1 | 10/3/2025 |
Info
- Last updated 15 days ago
- License
- Download package
Statistics
- Total Downloads
- 1
- Current Version Downloads
- 1
Authors
George Rios