Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
315 views
in Technique[技术] by (71.8m points)

c# - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...