Nullable Types

Wrapping settings retrieved from the database in a Property and storing them in Private local variables is a good thing. If the variable is still set to its default value, we populate from the database. Good times.

Private Shared _someSetting As Integer = 0
Public Shared ReadOnly Property SomeSetting As Integer
    Get
        If _someSetting = 0 Then
            _someSetting = GetSomethingFromTheDatabase()
        End If
        Return _someSetting
    End Get
End Property

But what if the actual stored value is 0? It’ll reload from the database every time. Enter the Nullable Type: Nullable Value Types (Visual Basic) Nullable Types (C#)

Private Shared _someSetting As Nullable(Of Integer)
Public Shared ReadOnly Property SomeSetting As Integer
    Get
        If Not _someSetting.HasValue Then
            _someSetting = GetSomethingFromTheDatabase()
        End If
        Return _someSetting.Value
    End Get
End Property

It’s just like a normal Integer, plus it can also be Nothing. Now we populate the variable only if it actually has not been set, then we return the Value of the Nullable Type.

You can also shortcut the declaration like this:

Private Shared _someSetting As Integer?

As the name implies, you can use the Nullable Type with any Value Type: Value Types and Reference Types.