ZetCode

F# null and nullable

last modified December 4, 2026

In this article we work with null in F#: where it comes from, how to check for it, and how to keep it out of F# code.

null is a reference that points to no object. F# itself does not need it, because a missing value is an option. But F# runs on .NET, where strings, arrays, and classes may be null and many library methods return it. Code that dereferences such a value fails with a NullReferenceException. F# 9 added nullable reference types, which let the compiler track possible nulls.

Null in .NET types

.NET reference types, such as string, accept the null literal. The isNull function tests for it.

null_string.fsx
let name: string = null
let city = "Bratislava"

printfn "%b %b" (isNull name) (isNull city)
printfn "%A" name
printfn "[%s]" name
printfn "%d" (String.length name)

let words: string[] = Array.zeroCreate 3
printfn "%A" words

The %A format prints <null>, while %s prints a null string as an empty one. Functions in the F# String module treat null as an empty string. Array.zeroCreate fills a new array with the default value of the element type, which for strings is null.

λ dotnet fsi null_string.fsx
true false
<null>
[]
0
[|null; null; null|]

F# types do not allow null

Types defined in F#, such as records, unions, and classes, do not have null as a proper value. The compiler rejects the literal.

no_null.fsx
type Point = { X: int; Y: int }

let p: Point = null

This is one of the reasons why null errors are rare in F# code: a function that takes a Point never receives a null one from other F# code.

λ dotnet fsi no_null.fsx
no_null.fsx(3,16): error FS0043: The type 'Point' does not have 'null' as a proper value

Checking for null

A null pattern in a match expression tests for null. For strings, .NET also has String.IsNullOrEmpty and String.IsNullOrWhiteSpace.

checks.fsx
open System

let describe (s: string) =
    match s with
    | null -> "null"
    | "" -> "empty"
    | s when String.IsNullOrWhiteSpace s -> "blank"
    | s -> sprintf "text '%s'" s

let inputs = [ null; ""; "   "; "owl" ]

for s in inputs do
    printfn "%-11s empty: %-5b blank: %b"
        (describe s) (String.IsNullOrEmpty s) (String.IsNullOrWhiteSpace s)

The patterns are checked from top to bottom, so null is handled first. IsNullOrWhiteSpace is true for null, empty, and blank strings, which makes it a good check for user input.

λ dotnet fsi checks.fsx
null        empty: true  blank: true
empty       empty: true  blank: true
blank       empty: false blank: true
text 'owl'  empty: false blank: false

NullReferenceException

Accessing a member of a null reference throws a NullReferenceException. The error appears where the value is used, which may be far from where the null came from.

null_ref.fsx
let shout (s: string) = s.ToUpper() + "!"

let names = [ "hawk"; null; "owl" ]

for name in names do
    try
        printfn "%s" (shout name)
    with :? System.NullReferenceException as e ->
        printfn "error: %s" e.Message

let safeShout (s: string) =
    match s with
    | null -> "(nothing)"
    | s -> shout s

names |> List.map safeShout |> printfn "%A"

Catching the exception works, but checking for null before the call is better: safeShout handles the missing value as a regular case. Exceptions are covered in F# exceptions.

λ dotnet fsi null_ref.fsx
HAWK!
error: Object reference not set to an instance of an object.
OWL!
["HAWK!"; "(nothing)"; "OWL!"]

Null from .NET methods

Many .NET methods return null to say that there is no result. At this boundary we convert the value to an option with Option.ofObj, as shown in F# option type; the rest of the code then works with options only.

dotnet_nulls.fsx
open System
open System.IO

let editor = Environment.GetEnvironmentVariable "ZC_EDITOR"
printfn "editor: %A" editor

let parent = Path.GetDirectoryName "/"
printfn "parent of /: %A" parent

let found = Type.GetType "System.Guid"
let missing = Type.GetType "System.NoSuchType"
printfn "%A %A" (isNull found) (isNull missing)

let setting name fallback =
    Environment.GetEnvironmentVariable name
    |> Option.ofObj
    |> Option.defaultValue fallback

printfn "editor: %s, shell: %s" (setting "ZC_EDITOR" "nano") (setting "ZC_SHELL" "bash")

The documentation of a .NET method says when it may return null. The same applies to libraries written in C#: their string and class results may be null unless the library says otherwise.

λ dotnet fsi dotnet_nulls.fsx
editor: <null>
parent of /: <null>
false true
editor: nano, shell: bash

AllowNullLiteral

The [<AllowNullLiteral>] attribute lets an F# class or interface accept null, like a C# class. It exists mainly for code that is used from C# or passed to .NET APIs that expect null.

allow_null.fsx
[<AllowNullLiteral>]
type Node(name: string, next: Node) =
    member _.Name = name
    member _.Next = next

let third = Node("c", null)
let second = Node("b", third)
let first = Node("a", second)

let rec walk (node: Node) =
    if not (isNull node) then
        printfn "%s" node.Name
        walk node.Next

walk first

let rec length (node: Node) = if isNull node then 0 else 1 + length node.Next
printfn "length: %d" (length first)

The last node of the linked chain has null as its successor. In code meant only for F#, an Node option field expresses the same thing without null.

λ dotnet fsi allow_null.fsx
a
b
c
length: 3

Unchecked.defaultof

Unchecked.defaultof returns the .NET default value of a type: zero for numbers and null for every reference type, including F# records. It bypasses the rule that F# types are never null.

default_of.fsx
type Point = { X: int; Y: int }

let n = Unchecked.defaultof<int>
let s = Unchecked.defaultof<string>
let p = Unchecked.defaultof<Point>

printfn "%d %A" n s
printfn "%b" (obj.ReferenceEquals(p, null))
printfn "%d" p.X

The record value is null although the type system says that this cannot happen. We test it with obj.ReferenceEquals, because the null pattern and isNull do not accept a record; reading its field crashes. The function is meant for low-level code and interop; the 'T: null constraint in generic code is shown in F# generics.

λ dotnet fsi default_of.fsx
0 <null>
true
System.NullReferenceException: Object reference not set to an instance of an object.

Nullable value types

Value types, such as int and DateTime, cannot be null. .NET wraps them in Nullable<'T> to add a missing state; databases and C# code (int?) use it often.

nullable.fsx
open System

let age = Nullable 42
let unknown = Nullable<int>()

printfn "%b %b" age.HasValue unknown.HasValue
printfn "%d" age.Value
printfn "%d" (unknown.GetValueOrDefault -1)

let describe (n: Nullable<int>) =
    if n.HasValue then sprintf "%d years" n.Value else "unknown"

printfn "%s, %s" (describe age) (describe unknown)

let ages = [ age; unknown; Nullable 17 ]
let known = ages |> List.choose Option.ofNullable
printfn "%A" known
printfn "%A" (Option.toNullable (Some 3.5))

HasValue tells whether a value is present, and Value reads it; reading the value of an empty Nullable throws. Option.ofNullable and Option.toNullable convert between nullables and options, so List.choose can keep only the known ages.

λ dotnet fsi nullable.fsx
true false
42
-1
42 years, unknown
[42; 17]
3.5

Nullable operators

The standard operators do not accept Nullable values. The NullableOperators module adds variants with a question mark on the nullable side: ?+ takes a nullable on the left, +? on the right, and ?+? on both.

nullable_ops.fsx
open System
open Microsoft.FSharp.Linq.NullableOperators

let price = Nullable 120.0
let discount = Nullable<float>()

printfn "%A" (price ?* 0.9)
printfn "%A" (price ?-? discount)
printfn "%A" (price ?> 100.0)
printfn "%A" (discount ?> 100.0)

let total = price ?+ 30.0
printfn "%A" total

Arithmetic with a missing value gives a missing value, and a comparison with one gives false. The operators are mostly used in query expressions over databases, where columns may be null.

λ dotnet fsi nullable_ops.fsx
108.0
<null>
true
false
150.0

Nullable reference types

Since F# 9 the compiler can track nulls in reference types. With nullness checking on, string means a string that is never null, and string | null means one that may be. In a project the setting is <Nullable>enable</Nullable>; for scripts we pass --checknulls+ to F# Interactive.

nullness.fsx
let label (s: string | null) = s.ToUpper()

printfn "%s" (label "owl")

Calling ToUpper on a value that may be null is a nullness warning (FS3261); so is assigning null to a plain string. We add --warnaserror+, so they become errors and the script does not run; F# Interactive also prints each nullness warning twice. Without --checknulls+ the script compiles without a message.

λ dotnet fsi --checknulls+ --warnaserror+ nullness.fsx
nullness.fsx(1,32): error FS3261: Nullness warning: Possible dereference of a null value when accessing member 'ToUpper' on the nullable value 's' of type 'string | null'.

Handling nullable references

A value of type string | null must be checked before use. After a null pattern, the compiler knows that the remaining value is not null. The Null and NonNull active patterns and the nonNull function help as well.

nullness_ok.fsx
let label (s: string | null) =
    match s with
    | null -> "(none)"
    | s -> s.ToUpper()

let size (s: string | null) =
    match s with
    | Null -> 0
    | NonNull text -> text.Length

let names: (string | null) list = [ "owl"; null; "hawk" ]

for name in names do
    printfn "%-6s %d" (label name) (size name)

let dir = System.IO.Path.GetDirectoryName "/tmp/notes.txt"
printfn "%s" (nonNull dir)

let firstName = names |> List.tryPick Option.ofObj
printfn "%A" firstName

Path.GetDirectoryName is annotated in .NET to return string | null. nonNull asserts that the value is not null and throws if it is; we use it because a path with a directory part always has a parent. Option.ofObj turns string | null into a plain string option.

λ dotnet fsi --checknulls+ --warnaserror+ nullness_ok.fsx
OWL    3
(none) 0
HAWK   4
/tmp
Some "owl"

Cleaning data at the boundary

The last example reads customer rows from a legacy API that uses null for missing fields. One function converts each row into an F# record with options; everything after it is free of null.

customers.fsx
open System

type LegacyRow = { Id: int; Name: string | null; Email: string | null; Age: Nullable<int> }

type Customer = { Id: int; Name: string; Email: string option; Age: int option }

let fetchRows () : LegacyRow list =
    [ { Id = 1; Name = "Paul"; Email = "paul@example.com"; Age = Nullable 34 }
      { Id = 2; Name = "  Lucia "; Email = null; Age = Nullable() }
      { Id = 3; Name = null; Email = ""; Age = Nullable 19 }
      { Id = 4; Name = "Peter"; Email = " "; Age = Nullable 51 } ]

let text (s: string | null) =
    match s with
    | null -> None
    | s when String.IsNullOrWhiteSpace s -> None
    | s -> Some(s.Trim())

let toCustomer (row: LegacyRow) =
    match text row.Name with
    | None -> Error(sprintf "row %d: missing name" row.Id)
    | Some name ->
        Ok { Id = row.Id; Name = name; Email = text row.Email; Age = Option.ofNullable row.Age }

for result in fetchRows () |> List.map toCustomer do
    match result with
    | Ok c ->
        let email = c.Email |> Option.defaultValue "-"
        let age = c.Age |> Option.map string |> Option.defaultValue "?"
        printfn "%d %-6s %-17s %s" c.Id c.Name email age
    | Error msg -> printfn "skipped %s" msg

The text function maps null, empty, and blank strings to None and trims the rest. A row without a name becomes an Error; see F# Result type. With nullness checking on, the compiler would report any use of row.Name or row.Email without a check.

λ dotnet fsi --checknulls+ --warnaserror+ customers.fsx
1 Paul   paul@example.com  34
2 Lucia  -                 ?
skipped row 3: missing name
4 Peter  -                 51

Source

Null values - F# language reference

Nullable reference types - F# language reference

In this article we have seen where null comes from in F#, checked for it with patterns, isNull, and String.IsNullOrWhiteSpace, converted it to options at .NET boundaries, used [<AllowNullLiteral>] and Unchecked.defaultof, worked with Nullable<'T> and nullable operators, and turned on nullable reference types. Related articles are F# option type, F# exceptions, and F# generics.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all F# tutorials.