Search code examples
c#expression-trees

Expression.Body removes class on static method call


I have an Expression with a certain Lambda in it that looks like this:

Expression<Func<string[],int>> expression = p => int.Parse(p[0]) * int.Parse(p[1])

when I call expression.Body, I get:

(Parse(p[0]) * Parse(p[1]))

if the expression would be like this:

Expression<Func<string[],int>> expression = p => p[0].ToInt() * p[1]ToInt()

naturally, the expression cuts off the class from a static method and do with it something.

My question is, how can i get a string representation with the excluded class? where does it store the static method? can i string.Format() the properties to get the full body?

p.s. I don't need to run the expression, i know that it will work when I'll call expression.Invoke. since I'm using CodeDom, I need the exact expression body


Solution

  • Expression.ToString() will instantiate an ExpressionStringBuilder, which unfortunately is internal sealed so you can't do much about it.

    See the relevant source code.

    You can try the following workaround:

    • Create a subclass of ExpressionVisitor
    • Instantiate a StringBuilder in the constructor
    • Override VisitMethodCall to implement your logic and append the string to the StringBuilder. Use MethodInfo.DeclaringType to access the method's type.
    • For the other node types, just append node.ToString() to the StringBuilder (reuse the existing functionality).