Daniel A. White
Daniel A. White

Reputation: 190945

Expression to string

How can I get a string like

Namespace.IMyService.Do("1")

from the expression as demoed in this snip it:

IMyService myService = ...;
int param1 = 1;

myExpressionService.Get(c => myService.Do(param1));

I actually don't want to call Do unless a condition is met using the string that was generated.

Upvotes: 3

Views: 2978

Answers (3)

Cameron
Cameron

Reputation: 98746

This would also work (though it's not particularly elegant):

public static string MethodCallExpressionRepresentation(this LambdaExpression expr)
{
    var expression = (MethodCallExpression)expr.Body;

    var arguments = string.Join(", ", expression.Arguments.OfType<MemberExpression>().Select(x => {
        var tempInstance = ((ConstantExpression)x.Expression).Value;
        var fieldInfo = (FieldInfo)x.Member;
        return "\"" + fieldInfo.GetValue(tempInstance).ToString() + "\"";
    }).ToArray());

    return expression.Object.Type.FullName + "." + expression.Method.Name + "(" + arguments + ")";
}

You can call it like this:

Expression<Action> expr = c => myService.Do(param1));
var repr = expr.MethodCallExpressionRepresentation();    // Namespace.IMyService.Do("1")

Upvotes: 1

Snowbear
Snowbear

Reputation: 17274

You will have to traverse Expression trees. Here is some sample code:

internal static class myExpressionService
{
    public static string Get(Expression<Action> expression)
    {
        MethodCallExpression methodCallExpression = (MethodCallExpression)expression.Body;
        var method = methodCallExpression.Method;
        var argument = (ConstantExpression) methodCallExpression.Arguments.First();

        return string.Format("{0}.{1}({2})", method.DeclaringType.FullName, method.Name, argument.Value);
    }
}

It works if called in this way: string result = myExpressionService.Get(() => myService.Do(1));

The output is: Namespace.IMyService.Do(1)

You can extend/update it to handle your scenario.

Upvotes: 4

ChrisWue
ChrisWue

Reputation: 19020

You should be able to call .ToString() on the resulting expression. According to the MS documentation ToString() returns the textual representation of the expression. Have you tried that?

Upvotes: 0

Related Questions