Search code examples
c#control-flow

Later code affecting earlier code, debugger going in to code block it shouldn't be entering


I have the following code ...

var len = request.Code.Trim().Length;
if (len.Equals(0))
{
    throw new ArgumentOutOfRangeException("request.Code");
}

try
{
    var obj = _repository.GetSomething(request.Code);
    return Result.Success(obj);
}
catch (Exception)
{
    return Result.Failure(MessageCode.MissingData);
}

I am running through this code with the debugger (via a unit test) and it is going in to the if (len.Equals(0)) block when len is 3. I've also tried changing the if statements to if (string.IsNullOrWhitespace(request.Code)) and I get the same problem.

If I remove the try/catch and leave just the code within the try block, everything is fine.

So, can anyone explain what on earth is going on here?

EDIT: To clarify the value of request.Code is "WH1", therefore len is 3. Which is what the debugger tells me just before I try to step over the if statement.

EDIT 2: I was getting a failing test which is what led me to debug this code. But now the test is passing, I changed another piece of code not shown in my question. All my tests pass now but when I debug through it the debugger still looks as if it's executing the throw within the first if block. Very confusing, but if I step over the statement it carries on as I would have expected.

It appears to be a bug of some kind in the debugger as the code isn't being executed, merely the cursor is going to that code and doing nothing with it.


Solution

  • The code wasn't being run at all, the debugger was just going to that line but not actually executing the code.