Search code examples
c#parsingexpressionexpression-trees

Serialize Expression to access string


I'm working on something similar to a text templating engine.
I'm providing metadata from my server to the client to represent an javascript version of the access path for instance:

Say I have a DTO:

public class Employee
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

I have a mapping on the server which looks like so:

Expression<Func<Employee, string>> firstNameExpression = e => employee.FirstName;

When returned to the client I would like to return something similar a string representation of the expression

$"{nameof(Employee)}.{nameof(Employee.FirstName)}";

I would prefer not to have to parse the expression manually or walk the expression tree.

//e.g Pseudo Code

LambdaExpression expression
if(expression is MemberExpression expr)
{
   stringBuilder.Prepend(expr.Body.Member.Name)
}
//... Handle errors 

Is there a simple way to output and expression as if it were written in code in some way?


Solution

  • If you need to precisely serialize/deserialize the expression tree, Serialize.Linq library might help.

    If all you want is some kind of string representation for display purposes, then I would recommend the ExpressionTreeToString library that I've written:

    using ExpressionTreeToString;
    
    Console.WriteLine(firstNameExpression.ToString("C#"));
    /*
        e => e.FirstName
    */
    
    Console.WriteLine(firstNameExpression.ToString("Textual tree", "C#"));
    /*
        Lambda (Func<Employee, string>)
            · Parameters[0] - Parameter (Employee) e
            · Body - MemberAccess (string) FirstName
                · Expression - Parameter (Employee) e
    */
    

    There are various string representations available.

    (Disclaimer: I am the author of the latter library.)