.NET library that allows you to easily handle null values in C#.
- Handle
nullable
value and reference types - Easy "from value" creation or static
.None
stub - Built-in Json support
System.Text.Json
as Serialization and Deserialization
KutCode.Optionality is designed to work with net7.0
and higher.
Install KutCode.Optionality using NuGet Package Manager:
Install-Package KutCode.Optionality
Or via the .NET CLI:
dotnet add package KutCode.Optionality
All versions can be found here.
- Wrap all types for easy nullabillity checks
public Optional<Person> GetPerson()
{
Person? person = _context.GetPerson();
return Optional.From<Person>(person);
}
public static void Main()
{
var person = GetPerson();
if (person.HasValue) Console.WriteLine(person.Name);
else Console.WriteLine("Person is not presented");
}
- Stop use null return - prevent
NullReferenceException
public Optional<Person> GetAnyPerson()
{
try {
// anything wrong...
}
catch {
return Optional<Person>.None; // .HasValue will return false
}
}
- Cast Optional type to TValue implicitly if you need
public void Main()
{
Optional<Person> person = Optional.From(new Person());
HandlePerson(person); // implicit casting
}
public void HandlePerson(Person person)
{
// some actions
}
KutCode.Optionality allows you to use Optional<T>
in JSON-models.