4.8. System.Nullable<T>

With the introduction of version 2.0 of the .NET Framework, developers are finally provided with a solution to the age-old problem of dealing with nullable types. The basic issue here is that not all data types provide a mechanism for determining if they have a "null" value. Clearly, with objects, there's a well-defined means of making this determination. However, with an int data type, there's no predefined value that could be used to determine if that int has been assigned a value. To resolve this, Visual Studio 2005 is introducing a new Nullable type that provides a uniform way of determining if a value is null.

Although nullable types are not exactly a generics concept, they are implemented using generics. A type is made nullable using the built-in Nullable generic class (which is in the System namespace). This generic class will be used to keep track of when its underlying type is assigned a value. Consider this example:

[VB code]
Public Class MyTest
    Public Shared Sub NullableTest(ByVal intVal1 As Nullable(Of Int32), _
                                   ByVal intVal2 As Int32)
        If (intVal1.HasValue() = True) Then
            Console.WriteLine(intVal1)
        Else
            Console.WriteLine("Value1 is NULL")
        End If

        If (intVal2 > 0) Then
            Console.WriteLine(intVal2)
         Else
Console.WriteLine("Value2 is Null?")
         End If
    End Sub
End Class
[C# code] using System; public class MyTest { public static void NullableTest(Nullable<int> intVal1, int intVal2) { if (intVal1.HasValue == true) Console.WriteLine(intVal1); else Console.WriteLine("Value1 ...

Get Professional .NET 2.0 Generics now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.