Chapter 6: Debugging with Visual Studio

175

{

Console.WriteLine( "Found: {0} {1}", firstName, lastName);

customerFound = true;

}

VB:

Dim firstName As String = cust.FirstName.Trim()

Dim lastName As String = cust.LastName.Trim()

If (searchName = cust.FirstName) Then

Console.WriteLine( "Found: {0} {1}", cust.FirstName, cust.LastName)

customerFound = True

End If

Next

Notice that the fix was to use the string.Trim method to remove the extraneous space from the data, assigning the clean results to local variables. Trim defaults to using the space character but has overloads that allow you to specify a different character, just in case the actual character you saw in Figure 6-16 was something other than a space. The rest of the logic uses variables with the clean data.

3.Press F5 to run the program and see if the fix works. Unfortunately, you’re stopped in your tracks by the fact that a new error occurs: a NullReferenceException. Unlike runtime errors that give you wrong data, VS helps greatly by breaking on exceptions when they occur in the code. The next section describes this error, the NullReferenceException, in greater detail and provides information to help you deal with the problem when it occurs in your programs.

Debugging and Resolving

NullReferenceException Problems

Encountering a NullReferenceException in your code is a common occurrence, deserving some discussion to help you deal with these problems effectively. As described in Step 3 in the preceding section, VS will pause on a NullReferenceException when running

Page 198
Image 198
Microsoft 9GD00001 manual Debugging and Resolving NullReferenceException Problems, 175