Back to results for “Exception Handling”
C# › Extension Methods

How would you write extension methods to build a lightweight, fluent validation/guard-clause library?

Advanced

Answer

Chain extension methods on a generic wrapper (or directly on the value type being validated) where each validation method either RETURNS the original value (for chaining) or THROWS if the condition fails — producing concise, self-documenting validation code without a heavy external dependency.
public static class GuardExtensions {
  public static T NotNull<T>(this T value, string paramName) where T : class =>
    value ?? throw new ArgumentNullException(paramName);

  public static int Positive(this int value, string paramName) =>
    value > 0 ? value : throw new ArgumentOutOfRangeException(paramName, "Must be positive");
}

public Order(Customer customer, int quantity) {
  Customer = customer.NotNull(nameof(customer));
  Quantity = quantity.Positive(nameof(quantity));
}
Real-world example Building a lightweight, dependency-free set of reusable guard-clause validators for constructor and method argument checking.

Common follow-ups: How does this pattern compare to using the newer built-in ArgumentNullException.ThrowIfNull() helper method?