views:

42

answers:

1

I had some problems figuring out a good title, but hopefully the code examples in this post are clear enough.

Is it possible, with the help of expression trees (or some other technique), to traverse the whole method "call stack"? Worded differently: When I get an expression tree from an Action-delegate, I would like to traverse inside the statements which happen inside the delegate.

I think it's best to move into examples as soon as possible... I have an abstract class called Command. Inside the Command is the following method:

protected void Run()
{
    RunCommand (() => this.Execute());
}

Execute is an abstract method which is implement by my sub classes. Here's an example of one Execute-method:

    protected override void Execute()
    {
        var data = new RegistrationData {HomeTown = "town"};
        service.SendNewRegistration(data);
    }

In my RunCommand-method I would like to get my hands on the statements inside the Execute-method. The method is defined as following:

protected void RunCommand(Expression<Action> expression)
{
    // Is it possible to find out that we're calling SendNewRegistration
    // of a service-instance in our expression?

    expression.Compile().Invoke();
}

Before calling the Invoke, is it possible to find out what happens inside the sub classes Execute-method? What is declared, what methods are executed and what parameters are used?

I tried to extend the ExpressionVisitor to see what is happening and made it to log VisitMethodCall-executions:

    protected override Expression VisitMethodCall(MethodCallExpression m)
    {
        Debug.WriteLine(m.Method.Name);
        return m;
    }

And the output was: Execute. So that didn't take me far. Is it somehow possible to the reach the statements inside the Execute-method?

+2  A: 

No - you cannot do this. Expression trees only go as deep as the lambda itself.

Rob Fonseca-Ensor
Thanks for the answer. I remember reading somewhere that the future versions of .NET and C# would give us even more dynamic programming environment. Any ideas if the next release (5.0?) could move us into a direction where this would be possible?
Mikael Koskinen
Not so much a dynamic *language*, but the next version of C# is supposed to come with a very pluggable, customisable compiler (written in C#), similar to how Boo works now.
Rob Fonseca-Ensor
Ok, thanks for your answer.
Mikael Koskinen