Use the Option Wrapper
Learn an alternative to nullable references: the Option type.
We'll cover the following...
With C# 8.0 nullable references, we can tell when an object reference might be null
. We have type hints for that. The statement Movie movie
is different from the statement Movie? movie
.
We only have nullable references available if we’re using recent C# versions with .NET Core 3.0 and upward. But, if we’re using older versions, we can use an alternative from functional languages: the Option
type.
The Option
type
Functional languages, like F# or Haskell, use a different approach for null
and optional values. Instead of null
, they use an Option
or Maybe
type.
With the Option
type, we have a box that might have a value. It’s the same concept of nullable primitive types. We briefly mentioned them before. Let’s write an example using nullable int
to see how it relates to the Option
type.
<Project Sdk="Microsoft.NET.Sdk"><PropertyGroup><OutputType>Exe</OutputType><TargetFramework>net6.0</TargetFramework><ImplicitUsings>enable</ImplicitUsings></PropertyGroup></Project>
With nullable primitive types, we have the HasValue
property to check if a variable has a value different from null
before using it. It’s dangerous if we try to use the Value
property directly since it might be ...