The easiest way to convert Expression to Roslyn SyntaxTree :
- Convert
Expression to the appropriate source code. - Correct the source code of an expression using
CSharpSyntaxTree.ParseText() .
We basically reduced the problem to converting Expression to source code. Such a question has already been asked on SO. Among the answers, Steve Wilkes proposed his library of AgileObjects.ReadableExpressions. It basically provides one method of extending ToReadableString() on Expression :
I tried this library with different expressions and it works great.
Therefore, returning to you, a solution based on this library will be very simple:
- Install the AgileObjects.ReadableExpressions NuGet package.
Define the following extension method on Expression :
public static class ExpressionExtensions { public static SyntaxTree ToSyntaxTree(this Expression expression) { var expressionCode = expression.ToReadableString(); return CSharpSyntaxTree.ParseText(expressionCode); } }
Now you can try:
var p = Expression.Parameter(typeof(int), "p"); Expression assignment = Expression.Assign(p, Expression.Constant(1)); Expression addAssignment = Expression.AddAssign(p, Expression.Constant(5)); BlockExpression addAssignmentBlock = Expression.Block( new ParameterExpression[] { p }, assignment, addAssignment); SyntaxTree tree = addAssignmentBlock.ToSyntaxTree();
Such an expression will be converted to the following code:
var p = 1; p += 5;
which successfully understands the corresponding SyntaxTree .
CodeFuller
source share