### Default guard clause usage example Source: https://github.com/ardalis/guardclauses/blob/main/_autodocs/api-reference/guardclauseextensions-null.md Example usage of Guard.Against.Default for int, TimeSpan, and string parameters. Throws for TimeSpan.Zero and null reference types. ```csharp using Ardalis.GuardClauses; public void Configure(int port, TimeSpan timeout, string serviceName) { Port = Guard.Against.Default(port); Timeout = Guard.Against.Default(timeout); // throws for TimeSpan.Zero Name = Guard.Against.Default(serviceName); // throws for null } ``` -------------------------------- ### Zero usage example Source: https://github.com/ardalis/guardclauses/blob/main/_autodocs/api-reference/guardclauseextensions-negative-and-zero.md Example of using Guard.Against.Zero with a long input. Throws ArgumentException with the custom message when max is zero. ```csharp using Ardalis.GuardClauses; public long Allocate(long max) { return Guard.Against.Zero(max, nameof(max), "Max must not be zero."); } ``` -------------------------------- ### WhiteSpace guard usage example Source: https://github.com/ardalis/guardclauses/blob/main/_autodocs/api-reference/guardclauseextensions-empty-and-whitespace.md Example of using the WhiteSpace guard. Throws ArgumentException when the span is all whitespace or empty. ```csharp using Ardalis.GuardClauses; public void HandleCommand(ReadOnlySpan command) { Guard.Against.WhiteSpace(command, nameof(command)); // process the non-blank command } ``` -------------------------------- ### NegativeOrZero usage example Source: https://github.com/ardalis/guardclauses/blob/main/_autodocs/api-reference/guardclauseextensions-negative-and-zero.md Example usage of NegativeOrZero in a constructor to ensure quantity and unit price are strictly positive. Throws ArgumentException if either value is zero or negative. ```csharp using Ardalis.GuardClauses; public class Order { public Order(int quantity, decimal unitPrice) { // both must be strictly positive _quantity = Guard.Against.NegativeOrZero(quantity); _unitPrice = Guard.Against.NegativeOrZero(unitPrice); } } ``` -------------------------------- ### StringTooLong usage example Source: https://github.com/ardalis/guardclauses/blob/main/_autodocs/api-reference/guardclauseextensions-stringlength.md Example of using Guard.Against.StringTooLong to validate a display name length. Throws ArgumentException if displayName exceeds 50 characters. ```csharp using Ardalis.GuardClauses; public void SetDisplayName(string displayName) { DisplayName = Guard.Against.StringTooLong(displayName, 50, nameof(displayName), "Display name is limited to 50 characters."); } ``` -------------------------------- ### Using Guard.Against in a class constructor Source: https://github.com/ardalis/guardclauses/blob/main/_autodocs/api-reference/guard-and-iguardclause.md Example of using the Guard.Against singleton to validate constructor parameters with NullOrWhiteSpace and Negative guards. The guards return the validated value, which is assigned to properties. ```csharp using Ardalis.GuardClauses; public class Product { public Product(string name, decimal price) { Name = Guard.Against.NullOrWhiteSpace(name); Price = Guard.Against.Negative(price); } public string Name { get; } public decimal Price { get; } } ``` -------------------------------- ### Migration example from AgainstExpression to Expression Source: https://github.com/ardalis/guardclauses/blob/main/_autodocs/api-reference/guardclauseextensions-expression.md Shows how to migrate from the obsolete AgainstExpression to the new Expression method. Note the predicate must be inverted: old threw when func returned false, new throws when func returns true. ```csharp using Ardalis.GuardClauses; // old (obsolete): threw when func returned false // Guard.Against.AgainstExpression(d => d > 0, amount, "must be positive"); // new: throw when func returns true Guard.Against.Expression(d => d <= 0, amount, "must be positive"); ``` -------------------------------- ### StringTooShort usage example Source: https://github.com/ardalis/guardclauses/blob/main/_autodocs/api-reference/guardclauseextensions-stringlength.md Example of using Guard.Against.StringTooShort to validate a password length. Throws ArgumentException if password is shorter than 8 characters. ```csharp using Ardalis.GuardClauses; public void SetPassword(string password) { Password = Guard.Against.StringTooShort(password, 8, nameof(password), "Password must be at least 8 characters."); } ``` -------------------------------- ### Expression guard usage example Source: https://github.com/ardalis/guardclauses/blob/main/_autodocs/api-reference/guardclauseextensions-expression.md Example usage of Guard.Against.Expression. The func returns true for invalid states (e.g., discount over 50% or non-positive). exceptionCreator supplies a custom exception. ```csharp using Ardalis.GuardClauses; public void SetDiscount(decimal discount) { // func returns true for the invalid state (a discount over 50% is rejected) Discount = Guard.Against.Expression(d => d <= 0m || d > 0.5m, discount, "Discount must be greater than 0% and at most 50%."); } public void SetEmail(string email) { Guard.Against.Expression(IsInvalidEmail, email, "Not a valid email address.", exceptionCreator: () => new ValidationException("Bad email")); } static bool IsInvalidEmail(string e) => !e.Contains('@'); ``` -------------------------------- ### LengthOutOfRange usage example Source: https://github.com/ardalis/guardclauses/blob/main/_autodocs/api-reference/guardclauseextensions-outofrange.md Example showing how to call Guard.Against.LengthOutOfRange with a custom message. Throws ArgumentException when the length is outside the inclusive bounds or when minLength exceeds maxLength. ```csharp using Ardalis.GuardClauses; public void SetUsername(string username) { Username = Guard.Against.LengthOutOfRange(username, 3, 20, nameof(username), "Username must be between 3 and 20 characters."); } ``` -------------------------------- ### InvalidFormat usage examples Source: https://github.com/ardalis/guardclauses/blob/main/_autodocs/api-reference/guardclauseextensions-format-and-validation.md Two usage examples of Guard.Against.InvalidFormat. The first requires a full-string match of exactly 16 digits for a card number. The second uses a custom exception creator for an ISBN-13 check. ```csharp using Ardalis.GuardClauses; public void ProcessCard(string cardNumber) { // full-string match required: exactly 16 digits Guard.Against.InvalidFormat(cardNumber, nameof(cardNumber), @"^\d{16}$", "Card number must be 16 digits."); } public void Import(string isbn) { Guard.Against.InvalidFormat(isbn, nameof(isbn), @"^\d{13}$", exceptionCreator: () => new FormatException("ISBN-13 expected")); } ``` -------------------------------- ### Example: Guard.Against.OutOfRange with IEnumerable Source: https://github.com/ardalis/guardclauses/blob/main/_autodocs/api-reference/guardclauseextensions-outofrange.md Example usage of the OutOfRange overload for an enumerable of integers. Throws if any element is less than 0 or greater than 100. ```csharp using Ardalis.GuardClauses; using System.Collections.Generic; public void SetScores(IEnumerable scores) { ScoreHistory = Guard.Against.OutOfRange(scores, nameof(scores), 0, 100); // throws if any element is < 0 or > 100 } ``` -------------------------------- ### Negative guard usage example Source: https://github.com/ardalis/guardclauses/blob/main/_autodocs/api-reference/guardclauseextensions-negative-and-zero.md Example using Guard.Against.Negative with decimal and TimeSpan overloads. The decimal overload returns the validated value; the TimeSpan overload is called for its side effect. Throws ArgumentException when input is negative. ```csharp using Ardalis.GuardClauses; using System; public decimal ApplyRefund(decimal amount, TimeSpan processingWindow) { amount = Guard.Against.Negative(amount, nameof(amount)); Guard.Against.Negative(processingWindow, nameof(processingWindow)); // TimeSpan overload return amount; } ``` -------------------------------- ### InvalidInputAsync usage example Source: https://github.com/ardalis/guardclauses/blob/main/_autodocs/api-reference/guardclauseextensions-format-and-validation.md Example of using Guard.Against.InvalidInputAsync to validate a promotion code asynchronously. Throws ArgumentException with the custom message when the predicate fails. ```csharp using Ardalis.GuardClauses; using System.Threading.Tasks; public async Task ClaimPromoAsync(string code) { return await Guard.Against.InvalidInputAsync(code, nameof(code), async c => await promotionService.IsRedeemableAsync(c), "Promotion code cannot be redeemed."); } ``` -------------------------------- ### ExpressionAsync usage example Source: https://github.com/ardalis/guardclauses/blob/main/_autodocs/api-reference/guardclauseextensions-expression.md Example of using ExpressionAsync to validate a username asynchronously. The predicate checks uniqueness; if it returns true, an ArgumentException with the provided message is thrown. ```csharp using Ardalis.GuardClauses; using System.Threading.Tasks; public async Task RegisterAsync(string username) { var validated = await Guard.Against.ExpressionAsync(async u => !await IsUniqueAsync(u), username, "Username is already taken."); return validated; } static Task IsUniqueAsync(string u) => Task.FromResult(true); ``` -------------------------------- ### InvalidInput usage example Source: https://github.com/ardalis/guardclauses/blob/main/_autodocs/api-reference/guardclauseextensions-format-and-validation.md Example of using Guard.Against.InvalidInput to validate a coupon code against an allowed list. Throws ArgumentException with the custom message when the predicate fails. ```csharp using Ardalis.GuardClauses; public void ApplyCoupon(string code) { Code = Guard.Against.InvalidInput(code, nameof(code), c => codeRegistry.AllowedCodes.Contains(c), "Coupon code is not valid."); } ``` -------------------------------- ### NullOrInvalidInput usage example Source: https://github.com/ardalis/guardclauses/blob/main/_autodocs/api-reference/guardclauseextensions-null.md Shows how to call Guard.Against.NullOrInvalidInput with a predicate that must return true for the input to be valid. The predicate checks that quantity is greater than 0 and less than or equal to 100. ```csharp using Ardalis.GuardClauses; public void SetQuantity(int? quantity) { Quantity = Guard.Against.NullOrInvalidInput(quantity, nameof(quantity), q => q is > 0 and <= 100); // predicate must return true to pass } ``` -------------------------------- ### Guard.Against.NullOrEmpty Source: https://github.com/ardalis/guardclauses/blob/main/_autodocs/index.md Throws an exception if the input is null or empty. Supports string, Guid, and enumerable types. ```APIDOC ## Guard.Against.NullOrEmpty ### Description Throws an exception if the input is `null` or empty. Supports string, Guid, and enumerable types. ### Method `Guard.Against.NullOrEmpty(T input, string parameterName)` ### Parameters - **input** (T) - Required - The value to check for null or emptiness. - **parameterName** (string) - Required - The name of the parameter being checked. ### Exceptions - `ArgumentNullException` - Thrown when `input` is `null`. - `ArgumentException` - Thrown when `input` is empty (e.g., empty string, empty Guid, or empty enumerable). ### Example ```csharp Guard.Against.NullOrEmpty(name, nameof(name)); ``` ``` -------------------------------- ### NullOrOutOfRange usage example with nullable int Source: https://github.com/ardalis/guardclauses/blob/main/_autodocs/api-reference/guardclauseextensions-outofrange.md Example usage for a nullable int parameter. Throws ArgumentNullException if age is null, ArgumentOutOfRangeException if outside [0,150]. ```csharp using Ardalis.GuardClauses; public void SetAge(int? age) { Age = Guard.Against.NullOrOutOfRange(age, nameof(age), 0, 150); // throws ArgumentNullException if age is null, ArgumentOutOfRangeException if outside [0,150] } ``` -------------------------------- ### Empty guard usage examples Source: https://github.com/ardalis/guardclauses/blob/main/_autodocs/api-reference/guardclauseextensions-empty-and-whitespace.md Two examples: one with a custom message, one with a custom exception creator. The guard throws ArgumentException if input is empty, unless exceptionCreator is provided. ```csharp using Ardalis.GuardClauses; public int FindFirstWord(ReadOnlySpan line) { Guard.Against.Empty(line, nameof(line), "Line must not be empty."); int i = line.IndexOf(' '); return i; } // with custom exception public void Parse(ReadOnlySpan payload) { Guard.Against.Empty(payload, nameof(payload), exceptionCreator: () => new FormatException("Payload is empty")); } ``` -------------------------------- ### EnumOutOfRange usage example Source: https://github.com/ardalis/guardclauses/blob/main/_autodocs/api-reference/guardclauseextensions-outofrange.md Example showing how to call Guard.Against.EnumOutOfRange for an enum parameter and for a raw integer value. The second call throws when the value is not a defined enum member (e.g., 5). ```csharp using Ardalis.GuardClauses; public enum Priority { Low = 1, Medium, High } public void ApplyPriority(Priority priority, int rawValue) { Guard.Against.EnumOutOfRange(priority, nameof(priority)); Guard.Against.EnumOutOfRange(rawValue, nameof(rawValue)); // e.g. 5 throws } ``` -------------------------------- ### Using Guard.Against.Null with basic and nullable value type Source: https://github.com/ardalis/guardclauses/blob/main/_autodocs/api-reference/guardclauseextensions-null.md Example usage of Guard.Against.Null: basic call captures parameterName automatically, and the nullable value type overload returns the unwrapped value. Requires using Ardalis.GuardClauses. ```csharp using Ardalis.GuardClauses; public class Order { public Order(Customer customer) { // basic use; parameterName is captured automatically Customer = Guard.Against.Null(customer); // nullable value type overload returns the unwrapped value int? quantity = GetQuantity(); int q = Guard.Against.Null(quantity, nameof(quantity)); } public Customer Customer { get; } } ``` -------------------------------- ### Catch NotFoundException in consumer code Source: https://github.com/ardalis/guardclauses/blob/main/_autodocs/errors.md Wrap a Guard.Against.NotFound call in a try/catch to handle the custom Ardalis.GuardClauses.NotFoundException. The exception message is "Queried object {parameterName} was not found, Key: {key}". The example shows catching it and returning a NotFound result. ```csharp using Ardalis.GuardClauses; try { var order = Guard.Against.NotFound(id, _orders.Find(id)); } catch (NotFoundException ex) { // ex.Message == "Queried object … was not found, Key: 42" return NotFound(ex.Message); } ``` -------------------------------- ### Guard.Against.Null with custom exception and message Source: https://github.com/ardalis/guardclauses/blob/main/_autodocs/api-reference/guardclauseextensions-null.md Error handling example: passes a custom message and exceptionCreator to Guard.Against.Null. When input is null, the creator's exception (ValidationException) is thrown instead of ArgumentNullException. ```csharp // error handling with custom exception and message public void Ship(IAddress address) { Guard.Against.Null(address, nameof(address), message: "Shipping address is required.", exceptionCreator: () => new ValidationException("Address missing")); } ``` -------------------------------- ### Push NuGet package to nuget.org Source: https://github.com/ardalis/guardclauses/blob/main/nuget.txt Run from the /bin/release folder. Replace with your NuGet API key. The .nupkg file name includes the version. ```bash dotnet nuget push -s https://www.nuget.org/api/v2/package -k Ardalis.GuardClauses.1.0.1.nupkg ``` -------------------------------- ### NullOrEmpty usage example Source: https://github.com/ardalis/guardclauses/blob/main/_autodocs/api-reference/guardclauseextensions-null.md Example of using Guard.Against.NullOrEmpty with an IEnumerable and a string. The first call re-uses the validated enumerable; the second passes a custom message. The third call uses a Guid, which is not an IEnumerable, so this example is invalid for the IEnumerable overload. ```csharp using Ardalis.GuardClauses; using System.Collections.Generic; public decimal GetTotal(IEnumerable lines) { // re-uses the same enumerable afterwards; no enumeration side effects beyond Any() var validated = Guard.Against.NullOrEmpty(lines, nameof(lines)); return validated.Sum(l => l.Total); } public void Register(string email, Guid tenantId) { Guard.Against.NullOrEmpty(email, nameof(email), "An email address is required."); Guard.Against.NullOrEmpty(tenantId, nameof(tenantId)); } ``` -------------------------------- ### NullOrEmpty (Guid overload) Source: https://github.com/ardalis/guardclauses/blob/main/_autodocs/api-reference/guardclauseextensions-null.md Guards against null or empty Guid inputs. Returns the unwrapped Guid value or throws an exception if the input is null or Guid.Empty. ```APIDOC ## NullOrEmpty (Guid overload) ### Description Guards against null or empty Guid inputs. Returns the unwrapped Guid value or throws an exception if the input is null or Guid.Empty. ### Method Extension method on `IGuardClause` ### Signature ```csharp public static Guid NullOrEmpty(this IGuardClause guardClause, [NotNull][ValidatedNotNull] Guid? input, [CallerArgumentExpression("input")] string? parameterName = null, string? message = null, Func? exceptionCreator = null) ``` ### Parameters - `input` (Guid?) - Required - Value to check - `parameterName` (string?) - Optional - Name used in thrown exceptions (auto-captured if not provided) - `message` (string?) - Optional - Overrides `"Required input {parameterName} was empty."` - `exceptionCreator` (Func?) - Optional - Factory thrown in place of the standard exception ### Return Type `Guid` - `input.Value` (unwrapped) when valid. ### Throws - `ArgumentNullException` when `input` is `null` - `ArgumentException` when `input == Guid.Empty` (`message ?? $"Required input {parameterName} was empty."`) - The creator's exception when supplied. ``` -------------------------------- ### Entry point: Guard.Against.Null Source: https://github.com/ardalis/guardclauses/blob/main/_autodocs/index.md Shows the entry point for all guard clauses via the static Guard.Against property. Requires the Ardalis.GuardClauses namespace. ```csharp using Ardalis.GuardClauses; // entry point: Guard.Against.(...) Guard.Against.Null(order, nameof(order)); ``` -------------------------------- ### Pack NuGet package with version Source: https://github.com/ardalis/guardclauses/blob/main/nuget.txt Run from project root. Use the /p:Version parameter to set the package version. Update the .csproj file with version and release notes first. ```bash dotnet pack -c release /p:Version=1.0.0 ``` -------------------------------- ### OutOfRange usage example Source: https://github.com/ardalis/guardclauses/blob/main/_autodocs/api-reference/guardclauseextensions-outofrange.md Example of using Guard.Against.OutOfRange with a DateTime value and with an enum value. The method returns the validated input. The enum example shows that enum types satisfy IComparable. ```csharp using Ardalis.GuardClauses; public void SetBirthDate(DateTime birthDate) { var min = new DateTime(1900, 1, 1); BirthDate = Guard.Against.OutOfRange(birthDate, nameof(birthDate), min, DateTime.Today); // enum values also satisfy IComparable: Guard.Against.OutOfRange(priority, nameof(priority), Priority.Low, Priority.High); } ``` -------------------------------- ### Tag release in git Source: https://github.com/ardalis/guardclauses/blob/main/nuget.txt Create an annotated tag for the release. The -m message should include the version and target repository. ```bash git tag -a v1.2.4 -m "Published 1.2.4 to nuget.org" ``` -------------------------------- ### Push tags to remote Source: https://github.com/ardalis/guardclauses/blob/main/nuget.txt Push commits and tags to the remote repository. The --follow-tags flag ensures tags are pushed along with commits. ```bash git push --follow-tags ``` -------------------------------- ### Guard.Against.Default Source: https://github.com/ardalis/guardclauses/blob/main/_autodocs/index.md Throws an exception if the input is equal to the default value of its type or null. ```APIDOC ## Guard.Against.Default ### Description Throws an exception if the input is equal to `default(T)` or `null`. ### Method `Guard.Against.Default(T input, string parameterName)` ### Parameters - **input** (T) - Required - The value to check. - **parameterName** (string) - Required - The name of the parameter being checked. ### Exceptions - `ArgumentException` - Thrown when `input` is `null` or equal to `default(T)`. ### Example ```csharp Guard.Against.Default(id, nameof(id)); ``` ``` -------------------------------- ### Guard.Against.NegativeOrZero Source: https://github.com/ardalis/guardclauses/blob/main/_autodocs/index.md Throws an exception if the input is zero or negative. Supports int, long, decimal, float, double, and TimeSpan. ```APIDOC ## Guard.Against.NegativeOrZero ### Description Throws an exception if the input is zero or negative. Supports `int`, `long`, `decimal`, `float`, `double`, and `TimeSpan`. ### Method `Guard.Against.NegativeOrZero(int input, string parameterName)` `Guard.Against.NegativeOrZero(long input, string parameterName)` `Guard.Against.NegativeOrZero(decimal input, string parameterName)` `Guard.Against.NegativeOrZero(float input, string parameterName)` `Guard.Against.NegativeOrZero(double input, string parameterName)` `Guard.Against.NegativeOrZero(TimeSpan input, string parameterName)` ### Parameters - **input** (numeric type) - Required - The value to check. - **parameterName** (string) - Required - The name of the parameter being checked. ### Exceptions - `ArgumentException` - Thrown when `input` is zero or negative. ### Example ```csharp Guard.Against.NegativeOrZero(quantity, nameof(quantity)); ``` ``` -------------------------------- ### Guard.Against.Zero Source: https://github.com/ardalis/guardclauses/blob/main/_autodocs/index.md Throws an exception if the input is zero. Supports int, long, decimal, float, double, and TimeSpan. ```APIDOC ## Guard.Against.Zero ### Description Throws an exception if the input is zero. Supports `int`, `long`, `decimal`, `float`, `double`, and `TimeSpan`. ### Method `Guard.Against.Zero(int input, string parameterName)` `Guard.Against.Zero(long input, string parameterName)` `Guard.Against.Zero(decimal input, string parameterName)` `Guard.Against.Zero(float input, string parameterName)` `Guard.Against.Zero(double input, string parameterName)` `Guard.Against.Zero(TimeSpan input, string parameterName)` ### Parameters - **input** (numeric type) - Required - The value to check. - **parameterName** (string) - Required - The name of the parameter being checked. ### Exceptions - `ArgumentException` - Thrown when `input` is zero. ### Example ```csharp Guard.Against.Zero(quantity, nameof(quantity)); ``` ``` -------------------------------- ### OutOfSQLDateRange usage example Source: https://github.com/ardalis/guardclauses/blob/main/_autodocs/api-reference/guardclauseextensions-outofrange.md Example of using Guard.Against.OutOfSQLDateRange to validate a DateTime before assignment. Throws ArgumentOutOfRangeException if the value is outside the SQL Server datetime range (1753-01-01 to 9999-12-31 23:59:59.997). ```csharp using Ardalis.GuardClauses; public void SaveRecord(DateTime dateCreated) { _dateCreated = Guard.Against.OutOfSQLDateRange(dateCreated); } ``` -------------------------------- ### Guard.Against.AgainstExpression / Guard.Against.AgainstExpressionAsync (obsolete) Source: https://github.com/ardalis/guardclauses/blob/main/_autodocs/index.md Throws an exception if the provided function returns false for the input. These are obsolete and should be replaced with Expression. ```APIDOC ## Guard.Against.AgainstExpression / Guard.Against.AgainstExpressionAsync (obsolete) ### Description Throws an exception if the provided function returns `false` for the input. These are obsolete and should be replaced with `Expression`. ### Method `Guard.Against.AgainstExpression(T input, string parameterName, Func func)` `Guard.Against.AgainstExpressionAsync(T input, string parameterName, Func> func)` ### Parameters - **input** (T) - Required - The value to check. - **parameterName** (string) - Required - The name of the parameter being checked. - **func** (Func or Func>) - Required - A function that returns `false` to trigger the exception. ### Exceptions - `ArgumentException` - Thrown when `func(input)` returns `false`. ### Example ```csharp Guard.Against.AgainstExpression(value, nameof(value), v => v >= 0); ``` ``` -------------------------------- ### Guard.Against.Expression / Guard.Against.ExpressionAsync Source: https://github.com/ardalis/guardclauses/blob/main/_autodocs/index.md Throws an exception if the provided function returns true for the input. ```APIDOC ## Guard.Against.Expression / Guard.Against.ExpressionAsync ### Description Throws an exception if the provided function returns `true` for the input. The async version is for asynchronous predicates. ### Method `Guard.Against.Expression(T input, string parameterName, Func func)` `Guard.Against.ExpressionAsync(T input, string parameterName, Func> func)` ### Parameters - **input** (T) - Required - The value to check. - **parameterName** (string) - Required - The name of the parameter being checked. - **func** (Func or Func>) - Required - A function that returns `true` to trigger the exception. ### Exceptions - `ArgumentException` - Thrown when `func(input)` returns `true`. ### Example ```csharp Guard.Against.Expression(value, nameof(value), v => v < 0); ``` ``` -------------------------------- ### Guard.Against.NotFound Source: https://github.com/ardalis/guardclauses/blob/main/_autodocs/index.md Throws an exception if the lookup result is null. Supports string and struct keys. ```APIDOC ## Guard.Against.NotFound ### Description Throws an exception if the lookup result is `null`. Supports string and struct keys. ### Method `Guard.Against.NotFound(string key, IEnumerable collection, string parameterName)` `Guard.Against.NotFound(T key, IEnumerable collection, string parameterName)` ### Parameters - **key** (string or T) - Required - The key to look up. - **collection** (IEnumerable) - Required - The collection to search. - **parameterName** (string) - Required - The name of the parameter being checked. ### Exceptions - `NotFoundException` - Thrown when the key is not found in the collection. ### Example ```csharp Guard.Against.NotFound(id, items, nameof(id)); ``` ``` -------------------------------- ### Guard.Against.InvalidInput / Guard.Against.InvalidInputAsync Source: https://github.com/ardalis/guardclauses/blob/main/_autodocs/index.md Throws an exception if the predicate returns false for the input. ```APIDOC ## Guard.Against.InvalidInput / Guard.Against.InvalidInputAsync ### Description Throws an exception if the provided predicate returns `false` for the input. The async version is for asynchronous predicates. ### Method `Guard.Against.InvalidInput(T input, string parameterName, Func predicate)` `Guard.Against.InvalidInputAsync(T input, string parameterName, Func> predicate)` ### Parameters - **input** (T) - Required - The value to check. - **parameterName** (string) - Required - The name of the parameter being checked. - **predicate** (Func or Func>) - Required - A function that returns `true` if the input is valid. ### Exceptions - `ArgumentException` - Thrown when `predicate(input)` returns `false`. ### Example ```csharp Guard.Against.InvalidInput(age, nameof(age), a => a >= 0); ``` ``` -------------------------------- ### Guard.Against.Empty / Guard.Against.WhiteSpace (ReadOnlySpan) Source: https://github.com/ardalis/guardclauses/blob/main/_autodocs/index.md Throws an exception if the input span is empty or whitespace. Available only on net8.0 target. ```APIDOC ## Guard.Against.Empty / Guard.Against.WhiteSpace (ReadOnlySpan) ### Description Throws an exception if the input `ReadOnlySpan` is empty or consists only of whitespace. Available only on net8.0 target. ### Method `Guard.Against.Empty(ReadOnlySpan input, string parameterName)` `Guard.Against.WhiteSpace(ReadOnlySpan input, string parameterName)` ### Parameters - **input** (ReadOnlySpan) - Required - The span to check. - **parameterName** (string) - Required - The name of the parameter being checked. ### Exceptions - `ArgumentException` - Thrown when the span is empty or whitespace. ### Example ```csharp Guard.Against.Empty(span, nameof(span)); ``` ``` -------------------------------- ### Guard.Against.OutOfSQLDateRange / Guard.Against.NullOrOutOfSQLDateRange Source: https://github.com/ardalis/guardclauses/blob/main/_autodocs/index.md Throws an exception if the DateTime is outside the SQL Server range. ```APIDOC ## Guard.Against.OutOfSQLDateRange / Guard.Against.NullOrOutOfSQLDateRange ### Description Throws an exception if the `DateTime` is outside the SQL Server range. The `NullOrOutOfSQLDateRange` variant also checks for null. ### Method `Guard.Against.OutOfSQLDateRange(DateTime input, string parameterName)` `Guard.Against.NullOrOutOfSQLDateRange(DateTime? input, string parameterName)` ### Parameters - **input** (DateTime or DateTime?) - Required - The date to check. - **parameterName** (string) - Required - The name of the parameter being checked. ### Exceptions - `ArgumentException` - Thrown when the date is outside the SQL Server range. - `ArgumentNullException` - Thrown when `input` is `null` (for `NullOrOutOfSQLDateRange`). ### Example ```csharp Guard.Against.OutOfSQLDateRange(date, nameof(date)); ``` ``` -------------------------------- ### NotFound with struct key Source: https://github.com/ardalis/guardclauses/blob/main/_autodocs/api-reference/guardclauseextensions-notfound.md Throws NotFoundException when a lookup by struct key (e.g., int, Guid) returns null. The key is null-checked via Null, and the message includes the key stringified via ToString(). Supports a custom exceptionCreator. ```csharp public static T NotFound(this IGuardClause guardClause, [NotNull][ValidatedNotNull] TKey key, [NotNull][ValidatedNotNull]T? input, [CallerArgumentExpression("input")] string? parameterName = null, Func? exceptionCreator = null) where TKey : struct ``` ```csharp using Ardalis.GuardClauses; using System; public Product GetProduct(int productId) { return Guard.Against.NotFound(productId, _catalog.Find(productId)); } public User GetUserByGuid(Guid userId) { return Guard.Against.NotFound(userId, _users.Find(userId), nameof(userId), exceptionCreator: () => new KeyNotFoundException($"No user with id {userId}")); } ``` -------------------------------- ### NotFound(this IGuardClause, TKey key, T? input, string? parameterName = null, Func? exceptionCreator = null) where TKey : struct Source: https://github.com/ardalis/guardclauses/blob/main/_autodocs/api-reference/guardclauseextensions-notfound.md Guards against a null lookup result when using a struct key (e.g., int, Guid). Throws an ArgumentNullException if the key is null (only possible for Nullable), and a NotFoundException (or a custom exception) if the input is null. ```APIDOC ## NotFound(this IGuardClause, TKey key, T? input, string? parameterName = null, Func? exceptionCreator = null) where TKey : struct ### Description Guards against a null lookup result when using a struct key (e.g., int, Guid). Throws an ArgumentNullException if the key is null (only possible for Nullable), and a NotFoundException (or a custom exception) if the input is null. ### Method Extension method on `IGuardClause`. ### Signature ```csharp public static T NotFound(this IGuardClause guardClause, [NotNull][ValidatedNotNull] TKey key, [NotNull][ValidatedNotNull]T? input, [CallerArgumentExpression("input")] string? parameterName = null, Func? exceptionCreator = null) where TKey : struct ``` ### Parameters - `guardClause` (IGuardClause) - Required (receiver) - The guard clause instance (e.g., `Guard.Against`). - `key` (TKey, constrained `where TKey : struct`) - Required - The lookup key (e.g., `int`, `Guid`); null-checked via `Null(key, nameof(key))`. - `input` (T?) - Required - The lookup result; throws when `null`. - `parameterName` (string?) - Optional - Default: `null` (auto-captured) - Object name embedded in the `NotFoundException` message. - `exceptionCreator` (Func?) - Optional - Default: `null` - Factory thrown in place of `NotFoundException`. ### Return Type `T` — the non-null lookup result. ### Throws - `ArgumentNullException` - If `key` is null (only possible for `Nullable` arguments). - `NotFoundException` - If `input is null`; message `"Queried object {parameterName} was not found, Key: {key}"` with `key` stringified via `key.ToString()!`. - `Exception` (creator instance) - If `input is null` with `exceptionCreator` supplied. ### Examples ```csharp using Ardalis.GuardClauses; using System; public Product GetProduct(int productId) { return Guard.Against.NotFound(productId, _catalog.Find(productId)); } public User GetUserByGuid(Guid userId) { return Guard.Against.NotFound(userId, _users.Find(userId), nameof(userId), exceptionCreator: () => new KeyNotFoundException($"No user with id {userId}")); } ``` ``` -------------------------------- ### Guard.Against.StringTooShort / Guard.Against.StringTooLong Source: https://github.com/ardalis/guardclauses/blob/main/_autodocs/index.md Throws an exception if the string is shorter or longer than the specified bound. ```APIDOC ## Guard.Against.StringTooShort / Guard.Against.StringTooLong ### Description Throws an exception if the string is shorter or longer than the specified bound. ### Method `Guard.Against.StringTooShort(string input, string parameterName, int minLength)` `Guard.Against.StringTooLong(string input, string parameterName, int maxLength)` ### Parameters - **input** (string) - Required - The string to check. - **parameterName** (string) - Required - The name of the parameter being checked. - **minLength** (int) - Required - The minimum allowed length (for `StringTooShort`). - **maxLength** (int) - Required - The maximum allowed length (for `StringTooLong`). ### Exceptions - `ArgumentException` - Thrown when the string is too short or too long. ### Example ```csharp Guard.Against.StringTooShort(name, nameof(name), 3); Guard.Against.StringTooLong(name, nameof(name), 50); ``` ``` -------------------------------- ### Guard clauses in Order constructor Source: https://github.com/ardalis/guardclauses/blob/main/README.md Apply multiple guard clauses to validate constructor parameters, including NullOrWhiteSpace, NegativeOrZero, Zero, Negative, and OutOfSQLDateRange. ```csharp public class Order { private string _name; private int _quantity; private long _max; private decimal _unitPrice; private DateTime _dateCreated; public Order(string name, int quantity, long max, decimal unitPrice, DateTime dateCreated) { _name = Guard.Against.NullOrWhiteSpace(name); _quantity = Guard.Against.NegativeOrZero(quantity); _max = Guard.Against.Zero(max); _unitPrice = Guard.Against.Negative(unitPrice); _dateCreated = Guard.Against.OutOfSQLDateRange(dateCreated, dateCreated); } } ``` -------------------------------- ### Guard.Against.NullOrWhiteSpace Source: https://github.com/ardalis/guardclauses/blob/main/_autodocs/index.md Throws an exception if the input string is null, empty, or consists only of whitespace. ```APIDOC ## Guard.Against.NullOrWhiteSpace ### Description Throws an exception if the input string is `null`, empty, or consists only of whitespace characters. ### Method `Guard.Against.NullOrWhiteSpace(string input, string parameterName)` ### Parameters - **input** (string) - Required - The string to check. - **parameterName** (string) - Required - The name of the parameter being checked. ### Exceptions - `ArgumentException` - Thrown when `input` is `null`, empty, or whitespace. ### Example ```csharp Guard.Against.NullOrWhiteSpace(description, nameof(description)); ``` ``` -------------------------------- ### Guard.Against property Source: https://github.com/ardalis/guardclauses/blob/main/_autodocs/api-reference/guard-and-iguardclause.md Static read-only property that returns the singleton IGuardClause instance used to invoke all guard clauses. This is the entry point for all guard clause calls. ```APIDOC ## Guard.Against property ### Description Static read-only property that provides the entry point to all guard clauses. Returns the same singleton instance every time; stateless and safe for concurrent use. ### Definition ```csharp public static IGuardClause Against { get; } ``` ### Usage ```csharp using Ardalis.GuardClauses; public class Product { public Product(string name, decimal price) { Name = Guard.Against.NullOrWhiteSpace(name); Price = Guard.Against.Negative(price); } public string Name { get; } public decimal Price { get; } } ``` ### Behavior - Always returns the same singleton instance. - The instance is stateless; all guards are pure functions of their arguments. - The class is not publicly constructible; the sole instance is created by the property initializer. ``` -------------------------------- ### StringTooLong method signature Source: https://github.com/ardalis/guardclauses/blob/main/_autodocs/api-reference/guardclauseextensions-stringlength.md Signature of the StringTooLong guard. Throws ArgumentException if input length exceeds maxLength, or if maxLength <= 0. Does not check for null input. ```csharp public static string StringTooLong(this IGuardClause guardClause, string input, int maxLength, [CallerArgumentExpression("input")] string? parameterName = null, string? message = null, Func? exceptionCreator = null) ``` -------------------------------- ### NegativeOrZero(decimal) Source: https://github.com/ardalis/guardclauses/blob/main/_autodocs/api-reference/guardclauseextensions-negative-and-zero.md Guards against zero or negative decimal values. Throws an ArgumentException if the input is less than or equal to zero. ```APIDOC ## NegativeOrZero(decimal) ### Description Guards against zero or negative decimal values. Throws an ArgumentException if the input is less than or equal to zero. ### Method Extension method on IGuardClause ### Signature ```csharp public static decimal NegativeOrZero(this IGuardClause guardClause, decimal input, [CallerArgumentExpression("input")] string? parameterName = null, string? message = null, Func? exceptionCreator = null) ``` ### Parameters - `guardClause` (IGuardClause) - Required - The guard clause instance. - `input` (decimal) - Required - Value being validated. - `parameterName` (string?) - Optional - Name used in the thrown ArgumentException. Default: null (auto-captured). - `message` (string?) - Optional - Overrides the default error message. Default: null. - `exceptionCreator` (Func?) - Optional - Factory thrown in place of the standard exception. Default: null. ### Return Type decimal ### Throws - ArgumentException with message `message ?? $"Required input {parameterName} cannot be zero or negative."` when `input <= 0`. - The exception from `exceptionCreator` if provided. ### Example ```csharp using Ardalis.GuardClauses; public class Order { public Order(int quantity, decimal unitPrice) { _quantity = Guard.Against.NegativeOrZero(quantity); _unitPrice = Guard.Against.NegativeOrZero(unitPrice); } } ``` ``` -------------------------------- ### Guard class definition with Against property Source: https://github.com/ardalis/guardclauses/blob/main/_autodocs/api-reference/guard-and-iguardclause.md The Guard class implements IGuardClause and exposes a static read-only property 'Against' that returns a singleton instance. The private constructor prevents external instantiation. ```csharp /// /// An entry point to a set of Guard Clauses defined as extension methods on IGuardClause. /// /// See http://www.weeklydevtips.com/004 on Guard Clauses public class Guard : IGuardClause { /// /// An entry point to a set of Guard Clauses. /// public static IGuardClause Against { get; } = new Guard(); private Guard() { } } ``` -------------------------------- ### Guard.Against.NullOrInvalidInput Source: https://github.com/ardalis/guardclauses/blob/main/_autodocs/index.md Throws an exception if the input is null or fails a predicate. ```APIDOC ## Guard.Against.NullOrInvalidInput ### Description Throws an exception if the input is `null` or does not satisfy the provided predicate. ### Method `Guard.Against.NullOrInvalidInput(T input, string parameterName, Func predicate)` ### Parameters - **input** (T) - Required - The value to check. - **parameterName** (string) - Required - The name of the parameter being checked. - **predicate** (Func) - Required - A function that returns `true` if the input is valid. ### Exceptions - `ArgumentNullException` - Thrown when `input` is `null`. - `ArgumentException` - Thrown when `predicate(input)` returns `false`. ### Example ```csharp Guard.Against.NullOrInvalidInput(age, nameof(age), a => a >= 0); ``` ``` -------------------------------- ### Zero(decimal) Source: https://github.com/ardalis/guardclauses/blob/main/_autodocs/api-reference/guardclauseextensions-negative-and-zero.md Throws an ArgumentException if the input is zero. Negative values pass. ```APIDOC ## Zero(decimal) ### Description Throws an ArgumentException if the input is zero. Negative values pass. ### Method Extension method ### Signature ```csharp public static decimal Zero(this IGuardClause guardClause, decimal input, [CallerArgumentExpression("input")] string? parameterName = null, string? message = null, Func? exceptionCreator = null) ``` ### Parameters - `input` (decimal) - Required - Value being validated - `parameterName` (string?) - Optional - Name used in the thrown ArgumentException - `message` (string?) - Optional - Overrides "Required input {parameterName} cannot be zero." - `exceptionCreator` (Func?) - Optional - Factory thrown in place of the standard exception ### Return Type decimal ### Throws ArgumentException (message `message ?? $"Required input {parameterName} cannot be zero."`) or the creator's exception when `EqualityComparer.Default.Equals(input, default(T))` (exact zero; negative values pass). ### Example ```csharp using Ardalis.GuardClauses; public long Allocate(long max) { return Guard.Against.Zero(max, nameof(max), "Max must not be zero."); } ``` ``` -------------------------------- ### Custom guard extension recipe on IGuardClause Source: https://github.com/ardalis/guardclauses/blob/main/_autodocs/api-reference/guard-and-iguardclause.md Shows how to create a custom guard clause by extending IGuardClause. The extension method uses CallerArgumentExpression to capture the parameter name automatically, and the usage demonstrates both optional and explicit parameter name passing. ```csharp // Using the same namespace will make sure your code picks up your // extensions no matter where they are in your codebase. namespace Ardalis.GuardClauses { public static class FooGuard { public static void Foo(this IGuardClause guardClause, string input, [CallerArgumentExpression("input")] string? parameterName = null) { if (input?.ToLower() == "foo") throw new ArgumentException("Should not have been foo!", parameterName); } } } // Usage public void SomeMethod(string something) { Guard.Against.Foo(something); Guard.Against.Foo(something, nameof(something)); // optional - provide parameter name } ``` -------------------------------- ### Guard.Against.Negative Source: https://github.com/ardalis/guardclauses/blob/main/_autodocs/index.md Throws an exception if the input is negative. Supports int, long, decimal, float, double, and TimeSpan. ```APIDOC ## Guard.Against.Negative ### Description Throws an exception if the input is negative. Supports `int`, `long`, `decimal`, `float`, `double`, and `TimeSpan`. ### Method `Guard.Against.Negative(int input, string parameterName)` `Guard.Against.Negative(long input, string parameterName)` `Guard.Against.Negative(decimal input, string parameterName)` `Guard.Against.Negative(float input, string parameterName)` `Guard.Against.Negative(double input, string parameterName)` `Guard.Against.Negative(TimeSpan input, string parameterName)` ### Parameters - **input** (numeric type) - Required - The value to check. - **parameterName** (string) - Required - The name of the parameter being checked. ### Exceptions - `ArgumentException` - Thrown when `input` is negative. ### Example ```csharp Guard.Against.Negative(quantity, nameof(quantity)); ``` ``` -------------------------------- ### Zero(float) Source: https://github.com/ardalis/guardclauses/blob/main/_autodocs/api-reference/guardclauseextensions-negative-and-zero.md Throws an ArgumentException if the input is zero. Negative values pass. ```APIDOC ## Zero(float) ### Description Throws an ArgumentException if the input is zero. Negative values pass. ### Method Extension method ### Signature ```csharp public static float Zero(this IGuardClause guardClause, float input, [CallerArgumentExpression("input")] string? parameterName = null, string? message = null, Func? exceptionCreator = null) ``` ### Parameters - `input` (float) - Required - Value being validated - `parameterName` (string?) - Optional - Name used in the thrown ArgumentException - `message` (string?) - Optional - Overrides "Required input {parameterName} cannot be zero." - `exceptionCreator` (Func?) - Optional - Factory thrown in place of the standard exception ### Return Type float ### Throws ArgumentException (message `message ?? $"Required input {parameterName} cannot be zero."`) or the creator's exception when `EqualityComparer.Default.Equals(input, default(T))` (exact zero; negative values pass). ### Example ```csharp using Ardalis.GuardClauses; public long Allocate(long max) { return Guard.Against.Zero(max, nameof(max), "Max must not be zero."); } ``` ``` -------------------------------- ### Zero(double) Source: https://github.com/ardalis/guardclauses/blob/main/_autodocs/api-reference/guardclauseextensions-negative-and-zero.md Throws an ArgumentException if the input is zero. Negative values pass. ```APIDOC ## Zero(double) ### Description Throws an ArgumentException if the input is zero. Negative values pass. ### Method Extension method ### Signature ```csharp public static double Zero(this IGuardClause guardClause, double input, [CallerArgumentExpression("input")] string? parameterName = null, string? message = null, Func? exceptionCreator = null) ``` ### Parameters - `input` (double) - Required - Value being validated - `parameterName` (string?) - Optional - Name used in the thrown ArgumentException - `message` (string?) - Optional - Overrides "Required input {parameterName} cannot be zero." - `exceptionCreator` (Func?) - Optional - Factory thrown in place of the standard exception ### Return Type double ### Throws ArgumentException (message `message ?? $"Required input {parameterName} cannot be zero."`) or the creator's exception when `EqualityComparer.Default.Equals(input, default(T))` (exact zero; negative values pass). ### Example ```csharp using Ardalis.GuardClauses; public long Allocate(long max) { return Guard.Against.Zero(max, nameof(max), "Max must not be zero."); } ``` ```