Microsoft 9GD00001 Computer Accessories User Manual


 
178 Microsoft Visual Studio 2010: A Beginner’s Guide
Additionally, you can drill down into the customers collection in one of the debugging
windows, such as Autos, Locals, or Watch, inspecting the Customer object at index 1. If
you recall from Step 3 in the preceding sequence, the Customer object we’re interested
in is at index 1. This result tells us that LastName for this Customer was set to null at
the data source and there is nothing we can do to keep it from being set to null; another
case of bad data. If you see a trend, you would be correct; never trust data whether
it comes from a user on the front end or from the database on the back end. At this
point, we have all the information we need to fix the problem and make sure we don’t
accidentally call methods on null data.
Press SHIFT-F5 to stop debugging.
7. In this example, we’ll fix the problem by checking for null before using a variable and
then replacing null with a default value. Comment out the contents of the foreach loop
and replace it with the following code:
C#:
string firstName = string.Empty;
if (cust.FirstName != null)
{
firstName = cust.FirstName.Trim();
}
string lastName =
cust.LastName == null ?
"" : cust.LastName.Trim();
if (searchName == firstName)
{
Console.WriteLine(
"Found: {0} {1}",
firstName,
lastName);
customerFound = true;
}
VB:
Dim firstName As String = String.Empty
If (cust.FirstName IsNot Nothing) Then
firstName = cust.FirstName.Trim()
End If
Dim lastName As String