tags:

views:

382

answers:

2

I'm realtively new to c# expression. I have some class something like that

class SimpleClass
{
    private string ReturnString(string InputString)
    {
        return "result is: "+InputString;
    }

    public string Return(Expression exp)
    {
        LambdaExpression lambda = Expression.Lambda(exp);
        return lambda.Compile();
    }
}

Now, I would like to call this method Return with some paramter something (pseudo) like this:

      SimpleClass sc = new SimpleClass();
      Expression expression = Expression.MethodCall(//how to create expression to call SimpleClass.ReturnString with some parameter?);
     string result = sc.Return(expression);
    Console.WriteLine(result);

Thanks for help/answer.

Matt

+3  A: 

It would be better to enforce the exp signature as early as possible - i.e. as an Expression<Func<string>>

public string Return(Expression<Func<string>> expression)
{
    return expression.Compile()();
}

with either:

SimpleClass sc = new SimpleClass();
string result = sc.Return(() => sc.ReturnString("hello world"));
Console.WriteLine(result);

or:

SimpleClass sc = new SimpleClass();
Expression expression = Expression.Call(
    Expression.Constant(sc),           // target-object
    "ReturnString",                    // method-name
    null,                              // generic type-argments
    Expression.Constant("hello world") // method-arguments
);
var lambda = Expression.Lambda<Func<string>>(expression);
string result = sc.Return(lambda);
Console.WriteLine(result);

Of course, delegate usage (Func<string>) might work just as well in many scenarios.

Marc Gravell
+3  A: 

If your goal is to learn expressions, that's fine. But if your goal is to accomplish this particular task, then a delegate would be a more appropriate way to solve this problem.

Brian