Path: redb-route/redb.Route/Expressions/ExchangeExpression.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/ExchangeExpression.cs
----
using System;
using redb.Route.Abstractions;
using redb.Route.Core;
namespace redb.Route.Expressions;
///
/// An expression that evaluates a value from an exchange using a provided function delegate.
///
public class ExchangeExpression : Expression
{
private readonly Func _expressionFunc;
///
/// Initializes a new instance of the class.
///
/// A function that accepts an and returns a result.
/// Thrown when is null.
public ExchangeExpression(Func expressionFunc)
{
_expressionFunc = expressionFunc ?? throw new ArgumentNullException(nameof(expressionFunc));
}
///
/// Thrown when is null.
/// Thrown when the result cannot be cast to .
/// Thrown when the result cannot be converted to due to format issues.
/// Thrown when an unexpected conversion error occurs.
public override T Evaluate(IExchange exchange)
{
if (exchange == null)
throw new ArgumentNullException(nameof(exchange));
var result = _expressionFunc(exchange);
if (result is T typedResult)
{
return typedResult;
}
try
{
return (T)RouteDecimal.ChangeType(result, typeof(T));
}
catch (InvalidCastException)
{
throw new InvalidCastException($"Cannot cast or convert result to type {typeof(T).Name}.");
}
catch (FormatException)
{
throw new FormatException($"Result cannot be converted to type {typeof(T).Name} due to format issues.");
}
catch (Exception ex)
{
throw new InvalidOperationException($"An error occurred while converting result to type {typeof(T).Name}.", ex);
}
}
///
/// Always thrown because does not support setting values.
public override void SetValue(IExchange exchange, object value)
{
throw new NotSupportedException("ExchangeExpression does not support setting values.");
}
}