liveBook · Manning

Nullable type

As explained in F# in Action: A Revised Edition of Get Programming with F#

Nullable<T> is a .NET value type that represents either a value of a non-nullable value type or the absence of such a value.

A nullable type represents either a value-type value or the absence of a value. It lets application models represent unset numbers without reserving magic values such as -1, including values that originate in SQL databases. section 9.1.1

In F#, use Option throughout domain code rather than mixing Nullable<T>, naked nulls, and options. Convert at .NET boundaries, then convert back when returning data to .NET consumers. section 9.1.5

Convert nullable values at an F# boundary

Use Option.ofNullable to turn a .NET nullable into an F# option, and Option.toNullable when data must cross back into .NET code. This keeps missing-value handling uniform inside the F# domain. section 9.1.5

open System
 
let optionalName : string option = null |> Option.ofObj   #1
let optionalNameTwo = "Isaac" |> Option.ofObj             #2
let optionalAge = Nullable() |> Option.ofNullable         #3
let optionalAgeTwo = Nullable 123 |> Option.ofNullable    #4

Compare empty and populated Nullable values after converting them into options with Option.ofNullable; the same boundary pattern applies to .NET objects through Option.ofObj. section 9.1.5

How F# in Action: A Revised Edition of Get Programming with F# covers it

How deep it goes
Explains the modeling problem, historical solution, boundary conversions, and preferred F# usage without detailing Nullable<T> internals.
Examples
Uses magic integer values, SQL-originated missing numbers, and F# conversions for empty or populated Nullable values.
What it assumes
Distinguishes .NET value types, reference types, null, Nullable<T>, and F# option when choosing a missing-value representation.
What you can do after
Apply it via F# Option conversion functions at .NET boundaries while keeping domain modeling centered on options.
How it connects
Connects nullable types with F# option, null, reference types, non-nullable reference types, and SQL databases.

Also explained in

Compare how 3 books explain nullable type →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of F# in Action: A Revised Edition of Get Programming with F#. The section links point to the parts of the book it draws on.