Skip to content

libanvl/opt

Repository files navigation

.NET 6 CodeQL Nuget (with prereleases)

libanvl.Opt

A null-free optional value library for .NET.

  • An optional value is represented as the base type Opt<T>
  • Present values are represented as the derived type Opt<T>.Some
  • Missing values are represented as the static property Opt<T>.None

See the Examples Tests for more on how to use Opt.

Requirements

.NET 6

Releases

  • NuGet packages are available on NuGet.org
    • Embedded debug symbols
    • Source Link enabled
  • NuGet packages from CI builds are available on the libanvl GitHub feed

Features

  • Immutable
  • Use Opt<T> instead of T? for optional values
  • Implicit conversion from T to Opt<T>
  • Opts of IEnumerable<T> are iterable
  • Deep selection of properties in complex objects
  • SomeOrEmpty() for string and enumerables
  • SomeOrDefault() for any type
  • Change to a null with SomeOrNull()
  • Explicitly opt-in to exceptions with Unwrap()
  • Cast inner value to compatible type with Cast()

Examples

class Car
{
	public string Driver { get; set;}
}

public void AcceptOptionalValue(Opt<Car> optCar, Opt<string> optName)
{
	if (optCar is Opt<Car>.Some someCar)
	{
		someCar.Value.Driver = optName.SomeOrDefault("Default Driver");
	}

	if (optCar.IsNone)
	{
		throw new Exception();
	}

	// or use Unwrap() to throw for None

	Car bcar = optCar.Unwrap();
}

public void RunCarOperations()
{
	var acar = new Car();
	AcceptOptionalValue(acar, "Rick");

	Car? nocar = null;
	AcceptOptionalValue(nocar.WrapOpt(), None.String)

	// use Select to project to an Opt of an inner property
	Opt<string> driver = acar.Select(x => x.Driver);
}

public void OptsOfEnumerablesAreIterable<T>(Opt<List<T>> optList)
{
	// if optList is None, the enumerable is empty, not null
	foreach (T item in optList)
	{
		Console.WriteLine(item);
	}

	// this is equivalent
	foreach (T item in optList.SomeOrEmpty())
	{
		Console.WriteLine(item);
	}
}