C# 10: Validating Arguments with CallerArgumentExpression

Writing guard clauses like `ArgumentNullException.ThrowIfNull(value)` is great, but error messages often lack context. CallerArgumentExpression captures the expression text at compile time.

Example

public static void Validate(
    bool condition,
    [CallerArgumentExpression("condition")] string? expression = null)
{
    if (!condition)
        throw new ArgumentException($"Failed: {expression}");
}

// Usage
Validate(user.Age >= 18);
// Exception message: "Failed: user.Age >= 18"

Key Takeaways

  • Zero runtime overhead—it’s a compile-time feature.
  • Use in custom assertion libraries or fluent validation.

Discover more from C4: Container, Code, Cloud & Context

Subscribe to get the latest posts sent to your email.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.