Working with Nullable Types in C# : Page 3

Checking the HasValue Property
When you run the sample application in Listing 4, you'll see the output shown in Figure 2.

Figure 2. Sample Program Output: The output shows the difference in the values displayed in the SSN and BilledAmount properties in the PatientNullable and PatientNonNullable classes.

As Figure 2 shows, the PatientNonNullable class assigns a default (-1) value to the SSN property when the database contains a null value. In contrast, the PatientNullable class can accept and preserve the null value, showing clearly that the data is missing. Early .NET developers were forced to use extensive checks and assign specific values that represented null values in value types, but that's no longer necessary in C# 2.0. Instead, you can use nullable types to avoid both the exceptions that occur when assigning null column values to value types, and the need to assign substitute values.

Figure 3. System.InvalidOperationException: Removing the HasValue check in the GetNullablePatient() method causes the framework to throw a System.InvalidOperationException.

In the GetNullablePatient() method in Listing 4, notice the HasValue check which determines whether the fields SSN and BilledAmount contain valid values. If the code had not performed the HasValue check, the framework would have thrown a System.InvalidOperationException error. Figure 3 illustrates how to create that error and shows the corresponding exception message.

Assigning Nullable Types to UI Elements
Assigning a nullable type to a property of a user-interface element requires the same sort of check. Here's a modified version of the GetNullablePatient() method from a Windows Forms application that displays patient data like the console application:

Figure 4. Windows Forms Example: This application checks HasValue for the nullable ContactPerson, SSN, and BilledAmount fields, and when they're null, manually assigns a substitute value (0 in this case) for display in the controls.

Note how the code assigns nullable types to the control properties, executing a HasValue check for each value that might be null. When you execute the windows application, the output is similar to Figure 4.