176Microsoft Visual Studio 2010: A Beginner’s Guide
the program. In this particular example, VS pauses on the line that cleans LastName properties, repeated here for your convenience:
C#:
var firstName = cust.FirstName.Trim(); var lastName = cust.LastName.Trim();
VB:
Dim firstName As String = cust.FirstName.Trim()
Dim lastName As String = cust.LastName.Trim()
If you recall, the reason for calling Trim on the FirstName and LastName properties was to clean the data prior to performing further operations on that data. While we were concerned about FirstName, we also called Trim on LastName as well to help protect against invalid data there too, just to be safe. The following steps show you how to use VS to analyze the current situation and make an effective decision on an appropriate fix.
1.If VS isn’t running, restart the program and let it run until VS pauses with a NullReferenceException.
2.Hover the cursor over cust.LastName to view the value. Alternatively, you can look in one of the debugging windows to see the value. Observe that LastName is null.
This is the critical point in the analysis, finding the value that is null. It was clear that cust is not null because the previous statement, cleaning FirstName, executed without error as verified by inspecting the firstName variable. This example makes it very easy to find the null value because it occurred on the line where VS paused. In more challenging situations, you could be passing an object to a method in a
Once you’ve found the null value, you must understand why the code raised the NullReferenceException error. A null value is the absence of a value; nothing is assigned to the variable. If you try to reference a variable with null assigned to it, you will receive a NullReferenceException. This makes sense because you are trying to perform an operation on a variable that has no definition. In this particular example, LastName is null, but we’re still referencing LastName by calling the Trim method. This is illogical because there is not a string to trim; the string variable is set to null.