Skip to content

Instantly share code, notes, and snippets.

@habib-sadullaev
Created September 10, 2023 09:11
Show Gist options
  • Save habib-sadullaev/b85fc58cfa02340583f09e195332ede3 to your computer and use it in GitHub Desktop.
Save habib-sadullaev/b85fc58cfa02340583f09e195332ede3 to your computer and use it in GitHub Desktop.
using System;
using System.Linq;
using System.Linq.Expressions;
static class _
{
static void Deconstruct(this BinaryExpression x,
out ExpressionType type,
out Expression left,
out Expression right)
{
(type, left, right) = (x.NodeType, x.Left, x.Right);
}
static void Main()
{
Expression<Func<int, int>> expr = x => x + 5;
expr = Replace(expr);
var res = expr.Compile()(5);
Console.WriteLine(res);
}
public static Expression<Func<T, T>> Replace<T>(
Expression<Func<T, T>> node)
{
var body = node.Body switch
{
BinaryExpression(ExpressionType.Add, var left, _) =>
Expression.MakeBinary(ExpressionType.Multiply, left, left),
Expression e => e
};
return Expression.Lambda<Func<T, T>>(body, node.Parameters);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment