Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Debugger stepping in if statement and lambda expression

Using the following code as an example:

if (true)
{
    string foo = null;
    List<string> bar = new List<string>
    {
        "test"
    };
    bar.Any(t => t == foo);
}

If I run this program in a regular way (without a break point or any other interruption), everything works without exception or error (as you would expect it).

Now if I put a break point on the if statement and move the cursor to the curly brace as described in the following picture (using my mouse, not using F10, so skipping the if(true) statement):

enter image description here

I get an exception of type System.NullReferenceException when the debugger executes the statement string foo = null

It seems to be linked to the fact that the variable foo is used in the lambda expression inside the if statement. I have tested and reproduced this on Visual Studio 2012 and 2013 (pro and ultimate).

Any idea on why this could be happening?

like image 389
cheesemacfly Avatar asked Jun 13 '14 23:06

cheesemacfly


People also ask

How do you debug a lambda expression?

We can use different IDE's like Netbeans, IntelliJ, and Eclipse to debug the lambda expressions in Java. It is always possible to create multi-line lambda expressions and use print statements to display the values of a variable. The debugger can also provide additional information about the state of a java program.

How do you evaluate lambda expression in IntelliJ?

You can use the Run to cursor function on a lambda expression as well. You can use Ctrl+F8 to add a breakpoint. Then the lambda expression that the cursor is placed on will be selected in the list. Pressing Ctrl+F8 again will complete creating a breakpoint on the selected lambda.


1 Answers

The comments which conjecture that you are skipping the generation of the closure are correct. C# programs are not guaranteed to have any particular behavior when you move the instruction pointer. If it hurts when you do that, don't do it.

actually that is a small lie. There are guarantees. For example, you are guaranteed that doing so in a verifiable program will not corrupt the internal data structures of the clr. You are guaranteed that doing so will not misalign the stack. and so on. But no guarantees are expressed or implied wrt your data structures! You move the instruction pointer at your peril.

like image 139
Eric Lippert Avatar answered Nov 16 '22 01:11

Eric Lippert