If (false == true) executes block when throwing exception is inside

C#.NetVisual Studio.Net Core

C# Problem Overview


I have a rather strange problem that is occurring.

This is my code:

private async Task BreakExpectedLogic()
{
    bool test = false;
    if (test == true)
    {
        Console.WriteLine("Hello!");
        throw new Exception("BAD HASH!");
    }
}

Seems really simple, it shouldn't hit the Console.WriteLine or the throw. For some reason it's always hitting the throw.

If I move the throw into its own method then it works fine. My question is how is it ignoring the if block and hitting the throw new Exception:

Here is some evidence

EDIT 1: I've updated my code to include the signature, I've removed everything not related to this problem and ran it, it still happens.

C# Solutions


Solution 1 - C#

It seems to be the bug in async method, the code is not actually executed but debugger steps to the line with throw statement. If there are some lines of code before throw statement inside if these lines are ignored, debugger steps only to the line with throw statement.

Also, if you don't use variable - if (false) or if (true == false) then debugger steps to the correct line of code - to the closing curly brace.

This bug has been posted by @Matthew Watson to Visual Studio team (link is not available now).

Also, see similar question - Condition check in async method

EDIT (2017-10-06):

Issue cannot be reproduced in VS 2017 15.3.5 using .Net Framework 4.7. Seems like VS team has fixed this issue.

Solution 2 - C#

Just an addendum to the answer, I've recently encountered the same issue, and looked to the actual x86 code in the debugger, and it was generated in a weird way like this (simplified):

// if (...) {
0001: jne 0006
...
0006: jmp 0007
// }
0007: ret

So instead of directly jumping to the last instructions of the method, it does double jump, where I believe the second unconditional jump is mistakenly recognized as a part of the code inside if block.

So I would speculate that this bug might be related to JIT compiler.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGeorgeView Question on Stackoverflow
Solution 1 - C#Roman DoskochView Answer on Stackoverflow
Solution 2 - C#Serge SemenovView Answer on Stackoverflow