I would like to debug a lambda that is called in an expression tree. Unfortunately, the breakpoint is never hit.
Here's a full Console Program to play with:
private static void Main()
{
var evalAndWrite = EvalAndWrite(x => x + 1 /* a breakpoint here is never hit */);
evalAndWrite(1);
Console.ReadLine();
}
private static Action<int> EvalAndWrite(Expression<Func<int, int>> expr)
{
var result = Expression.Variable(typeof(int), "result");
var assign = Expression.Assign(result, expr.Body);
var writeLine = Expression.Call(typeof(Console), nameof(Console.WriteLine), null, result);
var body = Expression.Block(new[] {result}, assign, writeLine);
return Expression.Lambda<Action<int>>(body, expr.Parameters[0]).Compile();
}
If I set a breakpoint within the lambda (i.e. at x + 1
using F9) the whole line gets breaked at but not the lambda when it is actually being executed.
Looking at the debug view of the body
I see:
.Block(System.Int32 $result) {
$result = $x + 1;
.Call System.Console.WriteLine($result)
}
which indicates a copy-semantic: the logic of the lambda has been "inlined" and I suppose the connection to the original lambda is lost. Or would there be any trick to making debugging of the original lambda within Visual Studio possible?