Can I set a breakpoint when variable is getting a specific value in .NET?

 ̄綄美尐妖づ 提交于 2019-11-27 18:43:25
JaredPar

It is certainly possible to set a condition like a variable receiving a certain value. This is known as a breakpoint condition. To create one, do the following.

  • Set a break point at the point the variable changes
  • Right click on the break point and select "Condition"
  • Type in the conditional like "theNewValue == 42"

Now the breakpoint will only hit when your conditional evaluates to true.

The second item you asked for, breaking when a variable's value changes for any reason, is known as a data breakpoint. These are only available for C++ code. It's not an option in C#, VB.NET or any other managed language.

So long as you are using a Visual Studio edition other than Express, you can achieve this in C# using a breakpoint condition.

In the Breakpoint Condition dialog box, enter a valid expression in the Condition box, such as myLocalVariable > 1

and

...choose Has changed if you want to break when the value of the expression has changed.

To get to the Has changed option, right-click your breakpoint in the Breakpoints window and select Condition..., then check the screenshot below.

Add a breakpoint with F9 - right click it and select "Condition..." - now you can add a boolean condition and the breakpoint will only get hit if that condition evaluates to true.

Pedro Maia Costa

It depends on the scope of your breakpoint. If the variable is not local or not static you won't be able to.

To set the condition of a breakpoint, right click it and you should get this screen:

Pick Condition...

You can use conditional breakpoints. I know your question was specific to VS2010, but be aware that from VS2012 on, you have to switch to the Managed Compatibility Mode, to use conditional breakpoints in Visual Basic. Why and how is described here:

switching-to-managed-compatibility-mode-in-visual-studio-2013

You can do both of these things.

  1. Set the breakpoint in VS. Right click on the red dot in the margin and select Add Condition. In there you can say var==value and select "Is True".
  2. You can probably achieve this with the "Has Changed" option in the dialog above.

VSCode

In VisualStudio Code, you can set conditional breakpoints as follows:

  1. Click in gutter to create a red-dot breakpoint

  2. Choose Debug from left-side toolbar (icon: circle-slash over bug)

  3. There are four sections: Variables, Watch, Call Stack and Breakpoints

  4. Expand Breakpoints section so you can see the breakpoints

  5. Right-Click on the desired breakpoint

  6. Choose Edit Breakpoint...

  7. Set your condition and press <Enter>. For example:
    myvar == 1234
    or
    'stophere' in myvar
    etc

References:

https://code.visualstudio.com/docs/editor/debugging#_conditional-breakpoints

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!