Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / All-Topics

Breaking in Code for a Specific Class Instance using Conditional Expressions

4.60/5 (3 votes)
9 Aug 2017CPOL1 min read 7K  
How to break in code for a specific class instance using conditional expressions

Let me describe the problem in hand by presenting a concrete example here. Let’s say we have an Employee class as shown below. Note here that the Salary property is calculated based on certain class instance fields.

Here is how the class is consumed:

Let’s say there is an issue when calculating the Salary for Mr Problematic. There is not an issue with Salary for Mr Fine. The easiest way could be to add a break-point in the getter for Salary property, but then your code will stop here when Salary is computed for each Employee. Our interest is to only break when Salary is calculated for Mr Problematic. This is where a combination of Make Object ID and conditional break-point (using Conditional Expression) can come in handy.

In order to accomplish that, we first need to Make Object ID for Employee class instance for Mr Problematic. This can be accomplished during a debug session once problematic instance has been created as shown below:

You can verify that object ID for this instance is created from the datatip.

Now you can simply add a Conditional breakpoint at the getter for Salary property by using a Conditional Expression of true when this == $1.

At this point, you can simply hit F5. Your code will hit the breakpoint once the conditions are met. You can verify that it’s the right instance by inspecting the object itself in Watch window as shown below:

One downside of this approach is that you will have to Make Object ID every time for a different debug session. Otherwise, you will get the following warning:

Until next time, happy debugging.

Filed under: CodeProject, Debugging

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)