spinon
spinon

Reputation: 10847

Null Reference Exception in Visual Studio Debugging

I am trying to test some code and now visual studio is throwing a null reference exception on the following line:

List<int> liveIds = new List<int>();

I am starting to think that visual studio has old code that it is looking at because no matter how I have tried to declare this line it continues to throw a null reference exception on this line.

Anyone know something that I might be missing?

UPDATE: ok so I changed out the variable and now I can't get the same error to happen on the previous line. Now it is happening on this line.

enter image description here

Upvotes: 1

Views: 2743

Answers (2)

Andrius R.
Andrius R.

Reputation: 189

Maybe the debugger itself is producing the exception.

I got a very similar situation, where i'm assigning a value from a function and the exception occurs right after executing the function (the Locals window indicates that the function does return a value):

var xmlElement = Serialize(data);

From Disassembly it seems that the exception happens immediately after the assignment, but before the next line of code. I'm guessing this is where some debugger code gets executed:

Screenshot of disassembly

Maybe debugger did not expect for that line of code to be executed, because I altered the execution path with "Set Next Statement" command (moved from the "else" block into this one). Same thing happens if I alter the code (remove the "if") while the debug is running, but the problem does not repeat if I rerun the encompassing procedure after the edit.

Upvotes: 1

spinon
spinon

Reputation: 10847

Ok so after some testing, things worked once I refactored the code and extracted the following code to a new method:

        // remove hospitals that are not currently assigned to someone
        hospitalsToCheck.RemoveAll(
            h =>
            {
                return
                    !currentAssignments.Exists(
                        a => a.AssignmentGroup.AssignedUnitIds.Intersect(h.Units.Select(u => u.UnitId)).Any());
            });

It seems that when I had code that was manipulating the list in the same method that it was defined, that is when I was getting the null reference exception.

Upvotes: 2

Related Questions