Microsoft 9GD00001 Computer Accessories User Manual


 
Chapter 6: Debugging with Visual Studio 177
You want the NullReferenceException to be raised because it protects you from
performing an invalid operation in your code. After you’ve found the null value and
ascertained the reason, it’s time to find out why the value is null in order to make an
informed decision on a fix.
3. In the Immediate window, type the following command:
C#:
customers.IndexOf(cust)
VB:
?customers.IndexOf(cust)
This will return 1, which is the index of the current Customer record, cust, in the
collection customers. This will save a lot of time when trying to find this object in
the data.
4. The debugger is currently paused on the line that cleans LastName, where the
NullReferenceException occurred and there is a yellow arrow on the breakpoint.
With your mouse, drag the yellow error up to the line that calls GetCustomers. We’re
currently attempting to answer the question of where this value became null. If lucky,
we can stop this at the source and possibly find a bug where the value is inadvertently
set to null.
5. Press F11 to step into the GetCustomers method. VS will navigate to the first line of the
GetCustomer method.
6. Press F10 twice to see what values are being returned. This example is so simple that
you can visually see the data. However, in real scenarios, you will probably be running
code that makes the query to a database, or other data source, and might prepare that
data in a form digestible by any potential callers. In Chapter 7, you’ll learn more about
how to perform database queries, but we want to keep things simple for now so that
you won’t be distracted by details unrelated to the point of this exercise, which is
debugging. Therefore, we need to inspect the data to see if it is the source of the null
data by typing the following command into the Immediate window:
C#:
customers[1].LastName
VB:
?customers(1).LastName