From f70b07b8380b48c55eededb6f4426bd5d3bf5a0e Mon Sep 17 00:00:00 2001 From: Steve Smith Date: Tue, 1 Aug 2023 14:16:35 -0400 Subject: [PATCH] Fixes #253 --- .../GuardAgainstExpressionExtensions.cs | 22 +++++++++++++++++++ .../GuardAgainstExpression.cs | 10 +++++++++ 2 files changed, 32 insertions(+) diff --git a/src/GuardClauses/GuardAgainstExpressionExtensions.cs b/src/GuardClauses/GuardAgainstExpressionExtensions.cs index f2cfeacd..ae78d003 100644 --- a/src/GuardClauses/GuardAgainstExpressionExtensions.cs +++ b/src/GuardClauses/GuardAgainstExpressionExtensions.cs @@ -50,4 +50,26 @@ public static async Task AgainstExpressionAsync(this IGuardClause guardCla return input; } + + /// + /// Throws an if evaluates to false for given + /// + /// + /// + /// + /// + /// + /// The name of the parameter that is invalid + /// if the evaluates to true + /// + public static T AgainstExpression(this IGuardClause guardClause, Func func, + T input, string message, string paramName) where T : struct + { + if (!func(input)) + { + throw new ArgumentException(message, paramName); + } + + return input; + } } diff --git a/test/GuardClauses.UnitTests/GuardAgainstExpression.cs b/test/GuardClauses.UnitTests/GuardAgainstExpression.cs index e5fa6ed2..794ef445 100644 --- a/test/GuardClauses.UnitTests/GuardAgainstExpression.cs +++ b/test/GuardClauses.UnitTests/GuardAgainstExpression.cs @@ -74,4 +74,14 @@ public void ErrorMessageMatchesExpected(string customMessage, string expectedMes Assert.NotNull(exception.Message); Assert.Equal(expectedMessage, exception.Message); } + + [Fact] + public void ErrorIncludesParamNameIfProvided() + { + string paramName = "testParamName"; + var exception = Assert.Throws(() => Guard.Against.AgainstExpression(x => x == 1, 2, "custom message", paramName)); + Assert.NotNull(exception); + Assert.NotNull(exception.Message); + Assert.Equal(paramName, exception.ParamName); + } }