Patrick
Patrick

Reputation: 5592

Using Linq to pass in a method

Is it possible to send an expression to a method, get the method name and the execute the expression and return the result?

The idea:

internal T Execute<T>(Expression expr)
{
    // Get method name and the parameters from the expression.
    // Check the methodname+parameters against the db

    // Execute the expression and return T
    return Expression.Execute(expr);
}

The call would look like this:

Expression<Func<string, string, Guid>> myExpression2 = (a, b) => PostMessage(a, b, 1);

return Execute<Guid>(myExpression2);

The calls will also have different return types, in this case its a guid. This would let me check the expression method in the execute method and determine if there is some extra logging needed or if something needs extra authentication.

The expressions always calls a method, like PostMessage, GetMessages or similar.

Upvotes: 0

Views: 140

Answers (1)

Lorenzo Dematt&#233;
Lorenzo Dematt&#233;

Reputation: 7839

Yes, it is possible. The Expression is a kind of syntax tree. You can walk it and extract the info you need from it. If it is always in a form that you expect (always a single method call) it would be easier for you. You just have to look for a MethodCallExpression http://msdn.microsoft.com/en-us/library/system.linq.expressions.methodcallexpression.aspx

MSDN has a nice example on how to do it (well, they also modify the tree: for you, it will be simpler, as you only need to read it and validate it, if I understood correctly) Here: http://msdn.microsoft.com/en-us/library/bb546136.aspx

Upvotes: 2

Related Questions