tags:

views:

162

answers:

4

Is is possible to scan a function provided as a lamba expression to figure out the nature of the function at runtime?

Example:

class Program
{
    static void Main(string[] args)
    {
        Examples example = new Examples(x => x ^ 2 + 2);
    }
}

public class Examples
{
    public Examples(Func<dynamic, dynamic> func)
    {
        // How can I scan "func" here to figure out that it is defined as "x => x ^ 2 + 2" instead of, say, as "x => Math.Exp(x)"?
    }
}
+4  A: 

You need to use expression trees, like this:

public Examples(Expression<Func<dynamic, dynamic>> func) {
    ...
}

For more information, see here.

SLaks
A: 

Take a look at this link:

http://msdn.microsoft.com/en-us/library/bb397951.aspx

Basically you wrap your Func<> type inside an Expression<> type and use its properties to parse it.

Blindy
+1  A: 

What you are after is an expression tree, you could change your Example method signature to....

public Examples(Expression<Func<dynamic, dynamic>> exp)
{
  // Visit the expression in here...
}
Tim Jarvis
wow, gotta be fast in here....
Tim Jarvis
+1  A: 

you can examine the syntactical structure of a LambdaExpression by looking at the Parameters property and Body property. The Body is an Expression node representing the root of the function body's abstract syntax tree.

or use an ExpressionVisitor, which traverses the nodes in the expression tree. Example code here: http://msdn.microsoft.com/en-us/library/bb882521.aspx

jspcal