Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert an Expression Tree to Source Code string

Tags:

.net

lambda

I have a function that has the following signature...

public string DoJunk(Expression<Func<bool>> expression)

I'm trying to find a way to convert the "expression" parameter back to something resembling the original source code (or at least a c# representation of the original souce code). So, if someone calls the function like this...

DoJunk(() => (i + j) * 9 == Math.Round((double)j / (i - 3), 4))

...I'd like to be able to convert the expression to this...

(i + j) * 9 == Math.Round((double)j / (i - 3), 4)

Has anyone done this?

like image 377
herbrandson Avatar asked Sep 10 '09 00:09

herbrandson


People also ask

How do you run expression tree?

Expression trees that represent lambda expressions are of type LambdaExpression or Expression<TDelegate>. To execute these expression trees, call the Compile method to create an executable delegate, and then invoke the delegate.

What is expression tree with example?

The expression tree is a tree used to represent the various expressions. The tree data structure is used to represent the expressional statements. In this tree, the internal node always denotes the operators. The leaf nodes always denote the operands.

What is expression tree in C#?

Expression trees represent code in a tree-like data structure, where each node is an expression, for example, a method call or a binary operation such as x < y . You can compile and run code represented by expression trees.


1 Answers

I've just happened across this; I've written a free, open-source library which provides an extension method to create a source-code-like string from an Expression:

using AgileObjects.ReadableExpressions;

var myExpression = CreateBigExpressionTree();
var expressionSource = myExpression.ToReadableString();

I've written a blog about it, the source is on GitHub, there's a NuGet package containing the extension method, and I've written a set of Debugger Visualizers for VS 2010 -> 2019 which are in the Visual Studio Marketplace.

like image 177
Steve Wilkes Avatar answered Oct 07 '22 16:10

Steve Wilkes