Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Visual Studio showing wrong values while debugging?

I was debugging my code when I saw something weird. Basically it came down to this:

Weirdness

What you see here is an unsigned int with a negative value...

I also noticed that some surrounding variables didn't have a value pop-up(?) and others did. But this variable was the only one that had an impossible value.

How is this possible?

I only have C# Visual Studio 2010, so I don't know it this problem exists in other versions or for different languages. I'll change the title and tags accordingly if this is the case.

like image 982
Jordy Avatar asked Aug 08 '13 12:08

Jordy


2 Answers

Try to:

  • Clean solution
  • Rebuild solution
  • In no success - kill PDB files manually (or entire bin and obj folders) and rebuild

Hope that helps.

like image 185
Dmitry Pavlov Avatar answered Oct 27 '22 00:10

Dmitry Pavlov


While debugging, Visual Studio will keep track of every variable in the current context.

Consider the following piece of code:

void SomeMethod1()
{
    int j = 0;
}

void SomeMethod2()
{
    int i = 0;
}//Breakpoint on this line.

When the program breaks, the current context is SomeMethod2. At this point the developer is unable to check what the value of j would be. This is because int j is not a variable in the current context.

The actual reason behind OP's described behavior:

Visual Studio checks if the name of the variable exists in the current context and doesn't check if the variable itself exists in the current context.

So if we change the name of variable j to i in SomeMethod1, we can suddenly view its "value". Imagine how weird it would get if i in SomeMethod2 was a string:

enter image description here

When should you know this?

Whenever you have a piece of code where it's not immediately clear what the current context is. I encountered this problem in the following piece of code:

private double CalculateFast(double d)
{
    //Depending on the size of d, either [Method 1] or [Method 2] is faster.
    //Run them both and use the answer of the first method to finish.
    Tasks.Task.Factory.StartNew(() = >
    {
        //Method 1   
    }

    //Method 2

    return answer;
}

I was debugging Method 2 but I thought I could view the variables of Method 1 as well. But this wasn't the case because Method 1 has its own context.

like image 36
Jordy Avatar answered Oct 27 '22 00:10

Jordy