Microsoft 9GD00001 Computer Accessories User Manual


 
Chapter 6: Debugging with Visual Studio 179
If cust.LastName Is Nothing Then
lastName = ""
Else
lastName = cust.LastName.Trim()
End If
If (searchName = firstName) Then
Console.WriteLine(
"Found: {0} {1}",
cust.FirstName,
cust.LastName)
customerFound = True
End If
This code fixes the problem two different ways, giving you more than one way to
solve the problem, depending on the style you prefer. In essence, the solution checks
the FirstName and LastName properties to see if they are null (Nothing in VB). If
they are not null, we know the properties have valid strings and are safe to work with.
Otherwise, we return an empty string.
In VB, you use the Is and IsNot operators when working with Nothing, rather than
the respective == and != for working with C# null. Also, the VB Iif, which is the
equivalent of the C# ternary operator, evaluates both true and false expressions,
resulting in a NullReferenceException even if the false condition doesn’t execute.
Therefore, the preceding VB example uses the more verbose If Then Else syntax.
The choice to default to an empty string is specific to this example only. In practice,
you’ll have to look at your own situation to see if it makes sense to use a default value.
For example, the presence of a null value might represent an erroneous condition and
you might prefer to log the condition and not allow the user to continue with the current
operation. Another strategy might be to skip this record, processing all the others, and
then show the user a list of records that weren’t processed. You might want to fix the
problem with any or none of the ideas I have here, but my point is that you should think
about what working with a null value means to your particular situation and not think
that the only way to fix a null reference bug is the way we did here.
8. Press F5 to run the program. It will provide the following output:
Found: Jean
Victory!