TinyOptional 0.0.2
See the version list below for details.
dotnet add package TinyOptional --version 0.0.2
NuGet\Install-Package TinyOptional -Version 0.0.2
<PackageReference Include="TinyOptional" Version="0.0.2" />
<PackageVersion Include="TinyOptional" Version="0.0.2" />
<PackageReference Include="TinyOptional" />
paket add TinyOptional --version 0.0.2
#r "nuget: TinyOptional, 0.0.2"
#:package TinyOptional@0.0.2
#addin nuget:?package=TinyOptional&version=0.0.2
#tool nuget:?package=TinyOptional&version=0.0.2
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 returningnull
, anOptional<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 anOptional<T>
with or without an initial value.- Checking:
IsPresent()
,IsNotPresent()
. - Retrieving:
Get()
,GetOrThrow(exceptionSupplier)
,OrElse(...)
, etc. - Filtering:
Where(predicate)
returns an emptyOptional
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 | Versions 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. |
-
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.