TinyOptional 0.0.2

There is a newer version of this package available.
See the version list below for details.
dotnet add package TinyOptional --version 0.0.2
                    
NuGet\Install-Package TinyOptional -Version 0.0.2
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="TinyOptional" Version="0.0.2" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="TinyOptional" Version="0.0.2" />
                    
Directory.Packages.props
<PackageReference Include="TinyOptional" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add TinyOptional --version 0.0.2
                    
#r "nuget: TinyOptional, 0.0.2"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package TinyOptional@0.0.2
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=TinyOptional&version=0.0.2
                    
Install as a Cake Addin
#tool nuget:?package=TinyOptional&version=0.0.2
                    
Install as a Cake Tool

TinyOptional: A Lightweight C# "Maybe" / Optional Type

This library provides a simple Optional (a.k.a. “Maybe”) type for C#. It allows you to express the presence or absence of a value without resorting to null. If an Optional<T> has a value, you can safely work with that value; if it doesn’t, the library’s methods help gracefully handle the “no value” scenario.

Table of Contents


Why Use an Optional Type?

  • Clarity: Instead of passing null or returning null, an Optional<T> signals explicitly that the result might be absent.
  • Safety: Avoid NullReferenceException by forcing the developer to deal with the possibility of an empty value.
  • Functional Style: Where, Select, SelectMany, IfPresent, etc., allow fluent transformations and checks.

Key Features

  • Of, OfNullable, Empty: Create an Optional<T> with or without an initial value.
  • Checking: IsPresent(), IsNotPresent().
  • Retrieving: Get(), GetOrThrow(exceptionSupplier), OrElse(...), etc.
  • Filtering: Where(predicate) returns an empty Optional if the predicate fails.
  • Transforming: Select(...), SelectMany(...).
  • Conditional Actions: IfPresent(...), IfNotPresent(...), including async versions.
  • Extension Methods: FirstIfExists, LastIfExists for collections, IfAny for strings, etc.

Installation

  dotnet add package TinyOptional

Getting Started

Creating Optionals


// Throws an ArgumentNullException if `value` is null
var maybeTen = Optional<int>.Of(10);

// Allows null but returns an empty Optional
var maybeValue = Optional<string>.OfNullable(someString);

// A straightforward empty Optional
var none = Optional<int>.Empty();

Unboxing an optional

var tenMaybe = Optional<int>.Of(10);

# check if the value is present
bool hasValue = tenMaybe.IsPresent();   
bool noValue = tenMaybe.IsNotPresent();

# getting the value
if (tenMaybe.IsPresent())
{
    int ten = tenMaybe.Get();
}

While possible, this is not the suggested workflow, as it would be a glorified, more verbose null-check. Instead, use the methods below.

Unboxing with fallback or error handling

var empty = Optional<int>.Empty();

// Returns 42 if the Optional is empty
int value = empty.OrElse(42);

// In case the fallback is expensive to compute
int value2 = empty.OrElseGet(() => ComputeFallback(42));

// In case no fallback is possible
int value3 = empty.OrElseThrow(() => new Exception("No value available"));

Filtering with Where

It is possible to apply a where clause to an Optional, returning an empty Optional if the predicate fails.

var maybeTen = Optional<int>.Of(10);

// Returns an empty Optional if the value is not greater than 5
var filtered = maybeTen.Where(value => value > 5);

Mapping with Select

The content of an optional can be transformed using the Select method, before being boxed back into an Optional and eventually unboxed.


var maybeUniverse = Optional<Universe>.Of(new Universe()
{
    Age = 13.8
    AgeUnit = "billion years"
});

var age = maybeUniverse
    .Where(u => u.AgeUnit == "billion years")
    .Whre(u => u.Age > 13)
    .Select(u => u.Age)
    .OrElseThrow(() => new Exception("No universe found"));

Conditional Actions: IfPresent / IfNotPresent

The IfPresent and IfNotPresent methods allow you to execute an action if the Optional has a value or not, respectively.

var maybeTen = Optional<int>.Of(10);

maybeTen
    .IfPresent(value => Console.WriteLine($"The value is {value}"))
    .OrElse(() => Console.WriteLine("No value"));

Extension Methods

Collections

The library provides a few extension methods to work with collections of Optionals.

var fibonacci = new List<int>() = { 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 };

var firstEven = fibonacci
  .FirstIfExists(optional => optional.Where(value => value % 2 == 0))
  .OrElse(0);

Strings

The library provides a few extension methods to work with strings.

  var inputName = ReadInputName();
  
    var name = inputName
        .IfAny()
        .OrElse("No name provided");

License

TinyOptional is licensed under the GPL v3. By using or redistributing this library, you agree to comply with the terms of that license.

Product Compatible and additional computed target framework versions.
.NET net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • net9.0

    • No dependencies.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
2.0.2 5,846 5/13/2025
2.0.1 245 5/13/2025
2.0.0 248 5/13/2025
1.0.6 14,366 1/1/2025
1.0.5 121 1/1/2025
1.0.4 124 1/1/2025
1.0.3 121 1/1/2025
1.0.2 131 12/31/2024
1.0.1 126 12/31/2024
1.0.0 117 12/31/2024
0.0.2 99 12/31/2024
0.0.1 104 12/31/2024