Microsoft 9GD00001 Computer Accessories User Manual


 
Chapter 6: Debugging with Visual Studio 171
If (customerFound = False) Then
Console.WriteLine("Didn't find customer.")
End If
Console.ReadKey()
End Sub
End Module
Notice that the searchName variable is set to “Jean”. Within the loop, the searchName
is compared with the FirstName property of each Customer instance for equality. Here’s
the output from when the program runs:
Didn't find customer.
What is supposed to happen is that the program should find the matching record and
print it out, but that’s not what happens. Here is the first bug, and the following discussion
describes how to find the cause of the bug using the VS debugger.
Finding the Bug
At this point, we know there is a bug and it’s reproducible, meaning that we can use VS
to debug and find the cause of the problem. In this situation, the program is saying that it
didn’t find a Customer record or, in other words, there is no record with a FirstName of
Jean. However, we know for a fact that the data does include a customer whose FirstName
is Jean. We need to find out why the program cannot find it. The following steps show
how the VS debugger can help isolate the problem.
1. Start by setting a breakpoint on the foreach loop in the Main method. This wasn’t an
arbitrary decision. Instead, considering the nature of the problem, I selected a part of
the program that is likely to begin providing a cue to what the problem is. Looking at
the program, one of the reasons that the program might not find the searchName is that
we aren’t getting data, causing the program to not execute the body of the foreach loop.
2. Press F5 to run the program in debug mode. This will execute the program and make it
stop on the foreach loop, making it possible to look at program state.
3. After VS hits the breakpoint, hover over customers to see if there are any values.
You’ll observe that customers does have three values. The fact that there are customers
indicates that the foreach loop is executing and we’ve eliminated that as a possibility.