Introduce IncrementResult record and refactor TryIncrement to return structured result

This commit is contained in:
Thorsten Sommer 2025-08-21 16:20:01 +02:00
parent aba30f50c5
commit 28502f9019
Signed by: tsommer
GPG Key ID: 371BBA77A02C0108
2 changed files with 20 additions and 9 deletions

View File

@ -44,20 +44,20 @@ public static class ExpressionExtensions
/// <param name="data">The object that contains the property referenced by the expression.</param>
/// <typeparam name="TIn">The type of the object that contains the property to be incremented.</typeparam>
/// <typeparam name="TOut">The type of the property to be incremented.</typeparam>
/// <returns>True if the property was successfully incremented, otherwise false.</returns>
public static bool TryIncrement<TIn, TOut>(this Expression<Func<TIn, TOut>> expression, TIn data) where TOut : IBinaryInteger<TOut>
/// <returns>An IncrementResult object containing the result of the increment operation.</returns>
public static IncrementResult<TOut> TryIncrement<TIn, TOut>(this Expression<Func<TIn, TOut>> expression, TIn data) where TOut : IBinaryInteger<TOut>
{
// Ensure that the expression body is a member expression:
if (expression.Body is not MemberExpression memberExpression)
return false;
return new(false, TOut.Zero);
// Ensure that the member expression is a property:
if (memberExpression.Member is not PropertyInfo propertyInfo)
return false;
return new(false, TOut.Zero);;
// Ensure that the member expression has a target object:
if (memberExpression.Expression is null)
return false;
return new(false, TOut.Zero);;
// Get the target object for the expression, which is the object containing the property to increment:
var targetObjectExpression = Expression.Lambda(memberExpression.Expression, expression.Parameters);
@ -68,14 +68,15 @@ public static class ExpressionExtensions
// Was the compilation successful?
if (targetObject is null)
return false;
return new(false, TOut.Zero);;
// Read the current value of the property:
if (propertyInfo.GetValue(targetObject) is not TOut value)
return false;
return new(false, TOut.Zero);;
// Increment the value:
propertyInfo.SetValue(targetObject, value + TOut.CreateChecked(1));
return true;
var nextValue = value + TOut.CreateChecked(1);
propertyInfo.SetValue(targetObject, nextValue);
return new(true, nextValue);
}
}

View File

@ -0,0 +1,10 @@
using System.Numerics;
namespace AIStudio.Tools;
/// <summary>
/// Represents the result of an increment operation. It encapsulates whether the operation
/// was successful and the increased value.
/// </summary>
/// <typeparam name="TOut">The type of the incremented value, constrained to implement the IBinaryInteger interface.</typeparam>
public sealed record IncrementResult<TOut>(bool Success, TOut UpdatedValue) where TOut : IBinaryInteger<TOut>;