Skip to content

04. Types

David Shnayder edited this page Jan 4, 2024 · 1 revision

Types

This library contains 2 discriminate union types, to suit a wide variety of user needs.

1. Result / Result<T>

This type works by having a bool IsOk property, a string Message and if needed a T? Value property. This allows the type to remain the same regardless of error or success, thus it is performs way better than lambda-required-handling types, but is more suited when the consumer knows exactly how it works.

For example, when the Result<T> is a failure, T? Value will be null this means, that if someone skips the check or tries to access the value when the Result<T> is a failure, they will get an exception.

  • Both types are readonly structs but will throw an InvalidOperation exception if they are created using a default constructor. The only valid way to create them is using the static factory methods inside Result.
  • Both Result and Result<T> also have the methods .AsTask() and .AsValueTask() that wrap a Task or ValueTask around them to make them easier to use in non-async Task or ValueTask methods.
  • Result has an extension method called .WithValue(T Value, which will return a Result<T> with the same Message and IsOk values. However, it is not recommended to use as the performance is worse than the factory methods, and it allows adding a non-null Value to a failed Result which messes with the logic flow.

2. Either<T0, T1>

This type is your usual lambda-required-handling discriminated union type, similar to OneOf. However it only has an option for 2 types.

This type has implicit operators that cast any of T0 or T1 to the type, and requires the consumer to either use delegates to get access to each, or to force casting it one type or the other. As with OneOf this makes it a little bit safer to use but vastly impacts performance, especially if you need to take the output value of one of them and continue processing it outside the lambda, or if you want to propagate a certain result forward in the code flow.

Clone this wiki locally