Welcome to SGuard
SGuard is a lightweight, extensible guard clause library for .NET, providing expressive and robust validation for method arguments, object state, and business rules.
π Featuresβ
- Boolean Guards (
Is.*): Check conditions and get aboolback instead of an exception. - Throwing Guards (
ThrowIf.*): Throw when a condition is true, withCallerArgumentExpression-powered messages. - Any & All Guards: Predicate-based validation for collections (
IEnumerable<T>andReadOnlySpan<T>). - Comparison Guards:
OutOfRangeandBetween(inclusive),LessThan,LessThanOrEqual,GreaterThan,GreaterThanOrEqualfor anyIComparable<T>type,Negative,NegativeOrZeroandZerofor any number type, andEqual/NotEqual. Strings can be compared with aStringComparison. With a floating-pointNaNoperand,Is.*comparisons returnfalseandThrowIf.*comparisons throw. - Null/Empty Checks:
Null,NullOrWhiteSpace, andNullOrEmptyfor null, default values (0,Guid.Empty, ...), empty strings (whitespace is not empty), collections and spans. With a selector (o => o.Customer.Email,o => o.Items[0].Sku), SGuard follows the path through members, indexers and instance method calls, and anullon it counts as empty; a complex-type member counts as empty only when all of its readable properties are null or empty. - String and Enum Guards:
LongerThan,ShorterThanandNotDefined. - Input Validators:
Is.Email,Is.Url(http/httpsonly),Is.CreditCard(Luhn) andIs.Match(a regex with a match timeout). - Return Values: A passing
ThrowIf.*guard returns the checked value:Sku = ThrowIf.NullOrEmpty(sku);. - Custom Exception Support: Pass a factory (
() => new MyException(...)) that runs only when the guard fails, an exception instance, or an exception type. - Native AOT: Every guard except
NullOrEmptyselectors works in trimmed and Native AOT apps, checked in CI. - Callback Model: Unified
SGuardCallbackandGuardOutcomefor success/failure handling. - Expression Caching: Selectors are compiled once and cached by expression structure (thread-safe), including selectors that capture local variables or use operators such as
+and??. - Allocation-free Guards: A passing guard costs about as much as a hand-written
if(around a nanosecond) and allocates nothing. - Clear Exception Messages: Built-in exceptions derive from
ArgumentException(range checks fromArgumentOutOfRangeException) and name the failing argument expression; checked values are left out of messages by default. - Multi-targeting: Supports .NET 8, 9, and 10.
π¦ Quick Installβ
dotnet add package SGuard
π― Quick Exampleβ
public User CreateUser(CreateUserRequest req)
{
ThrowIf.Null(req);
return new User(
ThrowIf.NullOrWhiteSpace(req.Username),
ThrowIf.LessThan(req.Age, 13, () => new ArgumentException("User must be 13+.", nameof(req.Age))),
ThrowIf.NullOrEmpty(req.Email));
}
Upgrading from 0.x? See Upgrading to 3.0.
πΊοΈ Documentation Structureβ
- Getting Started: Installation, quick start, and why choose SGuard
- Core Concepts: Understanding guard methods, callbacks, custom exceptions
- Guides: Practical guides for common scenarios
- Advanced: Performance tuning and best practices
- Migration: Upgrading from 0.x to 3.0
- API Reference: Complete API documentation
- Community: Contributing, code of conduct, changelog
π¬ Get Helpβ
- Matrix Chat: #sguard:gitter.im
- GitHub Issues: Report bugs or request features
- GitHub Discussions: Ask questions and share ideas
π€ Contributingβ
We welcome contributions! See our Contributing Guide to get started.
π Licenseβ
SGuard is licensed under the MIT License.