• 10 hours
  • Medium

Free online content available in this course.

course.header.alt.is_video

course.header.alt.is_certifying

Got it!

Last updated on 8/6/19

Define conditional breakpoints

At the end of the previous chapter, you saw that an exception was thrown when the model’s CreateTask method was called with the value "sleep" in the VerifyAddTasks test from T_TodoModels.cs.:

foreach (var taskName in GetTaskNames())


{


model.CreateTask(taskName);


}

A breakpoint has been defined. Now, we’d like the foreach loop execution to pause only when taskName has this value.

To do this, right-click on the breakpoint’s red dot, and select Conditions:

Menu for defining a condition on a breakpoint
Menu for defining a condition on a breakpoint

We’re interested in two types of conditions – Conditional Expression and Hit Count:

Conditional expression types
Conditional expression types

The first allows the break condition to be defined, either when a boolean expression is true, or when its value has changed:

Condition on a Boolean expression
Condition on a Boolean expression

The expression taskName == “sleep” requires the debugger to stop when the value of taskName is equal to “sleep”:

Boolean expression based on comparison of a character string
Boolean expression based on comparison of a character string

Let’s look at another situation where we know which iteration of a loop to stop. You can use the second type of condition by indicating the number of times the debugger must pass the breakpoint before pausing execution:

Breakpoint condition based on an execution counter
Breakpoint condition based on an execution counter

In this example, it's set to pause before performing the fourth iteration of the breakpoint.

If you look at the unit test code, you’ll see that the GetTaskNames method, which returns the list of task names, sets the value “sleep” on the first and fourth iterations:

private IEnumerable<string> GetTaskNames()
{
   yield return "sleep";
   yield return "work";
   yield return "play Diablo";
   yield return "sleep";
}

Thus, this sort of conditional breakpoint allows pausing on the last value “sleep”.

Let's recap!

In this chapter, you’ve seen how to tell the debugger to pause code execution with instructions and conditions. We have everything ready to pause execution just before calling the instruction that will trigger the exception we’ve been hunting down ever since the start of this course! 🤩

However, we don’t know what to do to get out of the paused debugger: the next chapter will explain in detail how to run the execution step by step.

Example of certificate of achievement
Example of certificate of achievement