Path: redb-route/redb.Route/Expressions/DelegateExpression.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route/Expressions/DelegateExpression.cs ---- using System; using System.Collections.Generic; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Expressions; /// /// An expression based on a delegate (function) that evaluates its value from an . /// /// The return type of the delegate. public class DelegateExpression : Expression { private readonly Func _delegate; /// /// Initializes a new instance of the class with the specified delegate. /// /// A function that accepts an and returns a value of type . /// Thrown when is null. public DelegateExpression(Func @delegate) { _delegate = @delegate ?? throw new ArgumentNullException(nameof(@delegate)); } /// /// Thrown when the delegate result cannot be cast to . /// Thrown when the delegate execution fails. public override K Evaluate(IExchange exchange) { try { var result = _delegate(exchange); // If the result is null, return default(K) if (result == null) { return default; } if (result is K typedResult) { return typedResult; } // If K is some IEnumerable<> and result is a collection of another type, // try converting via reflection if (typeof(K).IsGenericType && typeof(K).GetGenericTypeDefinition() == typeof(IEnumerable<>) && result is System.Collections.IEnumerable collection) { // Element type of the target collection var targetElementType = typeof(K).GetGenericArguments()[0]; // Convert collection elements and return as IEnumerable var convertedList = Activator.CreateInstance(typeof(List<>).MakeGenericType(targetElementType)); if (convertedList != null) { var addMethod = convertedList.GetType().GetMethod("Add"); if (addMethod != null) { foreach (var item in collection) { if (item != null && item.GetType().IsAssignableTo(targetElementType)) { addMethod.Invoke(convertedList, new[] { item }); } } } if (convertedList is K listAsK) { return listAsK; } } } // Try standard type conversion return (K)RouteDecimal.ChangeType(result, typeof(K)); } catch (InvalidCastException) { throw; } catch (Exception ex) { // Wrap exceptions originating from inside the delegate throw new InvalidOperationException($"Error executing delegate expression: {ex.Message}", ex); } } /// /// Always thrown because a delegate expression is read-only. public override void SetValue(IExchange exchange, object value) { throw new NotSupportedException("Cannot set value on a delegate expression"); } }