11.2. Nullable Types
Any developer who has worked with a database understands some of the pain that goes into aligning business objects with database schemas. One of the difficulties has been that the default value for a database column could be nothing (as in not specified), even if the column was an integer. In .NET, value types, such as integers, always have a value. When pulling information from the database, it was necessary to add additional logic that would maintain state for the database columns to indicate whether a value had been set. Two of the most prominent solutions to this problem were to either adjust the database schema to prevent nothing values, which can be an issue where a field is optional, or to add a Boolean flag for every field that could be nothing, which added considerable amounts of code to even a simple application.
Generic types provide a mechanism to bridge this divide in quite an efficient manner, using the generic Nullable type. The Nullable type is a generic structure that has a single Type parameter, which is the type it will be wrapping. It also contains a flag indicating whether a value exists, as shown in the following snippet:
Public Structure Nullable(Of T As Structure) Private m_hasValue As Boolean Private m_value As T Public Sub New(ByVal value As T) Me.m_value = value Me.m_hasValue = True End Sub Public ReadOnly Property HasValue() As Boolean Get Return Me.m_hasValue End Get End Property Public ReadOnly Property Value() As T Get If Not ...