Skip to content

Option

Represents a value that is either present or not present.

It is a struct, preventing you from returning null instead.

Can be used for value and reference types.

Extension Methods

Map - Option<T> -> Option<TR>

The Map extension methods allow you to transform an Option<T> to an Option<TR>.

The transformation will only occur if there is a value present.

Switch - Option<T> -> TR

The Switch extension methods allow you to transform an Option<T> to a TR.

You have to say what to return when the value is present and not present.

DoSwitch - Perform side-effect

The DoSwitch extension methods allow you to perform a side-effect on an Option<T>.

You have to say what to do when the value is present and not present.

TryGetValue - Get a value from a Dictionary

The TryGetValue extension methods work with dictionary.

They get the value from a dictionary as an Option<T>.

Factory - T -> Option<T>

There are a number of factory extension methods.

From

Converts a T to an Option<T>

If the value is not null, then it will be a Option<T> with the value on it.

If the value is null, then it will be a Option<T> with the value not set.

None

Returns a Option<T> with the value not set.

ToOption

Converts a T to an Option<T>

If the value is not null, then it will be a Option<T> with the value on it.

If the value is null, then it will be a Option<T> with the value not set.

Implicit conversion

There is an implicit conversion in place. So if your method returns an T, then it will be automatically converted to an Option<T>.

OrElse and GetValueOrDefault

The OrElse extension methods are good when you have a precedence order.

The GetValueOrDefault extension methods are used to as a terminating method and will take you out if an Option, returning the default value provided if the Option has no value.

TryParse

There are a lot of TryParse extension methods provided, for a lot of the built-in framework types:

  • Bool
  • Int
  • Long
  • Decimal
  • Double
  • Float
  • Guid
  • DateTime
  • DateOnly
  • TimeOnly
  • Enum

LINQ

TryElementAt

TryFirst

TryLast

TrySingle

Enumerable<Option<T>>

Choose

Map

MapSwitch

Pick

Interop with Nullable

For structs there is interop with Nullable

Nullable -> Option

Use the ToOption extension method.

Option -> Nullable

Use the ToNullable extension method.

Interop with Result

Option -> Result

You can move between an Option and a Result using the 'ToResult' extension method. You just need to provide the error if the Option is not present.

Result -> Option

This is not supported as it would result in the loss of the error context.