RustLikeReturnValues brings Rust-inspired Option<T> and Result<T, E> types to modern C#. The libraries focus on ergonomic APIs, predictable performance, and explicit success/failure handling.
RustLikeOption– expressive option type with helpers likeMap,AndThen,Filter, JSON converters, andIEnumerableinterop.RustLikeResult– rich result type with pattern matching, async helpers, JSON converters, and composition primitives.RustLikeExtension– utility extensions built on top of Option/Result, including collection helpers,Trywrappers, and the lightweightRLogger<T>.
- Keeps error handling explicit without exceptions dominating control flow.
- Encourages railway-oriented pipelines with fluent APIs.
- Minimises allocations for common paths; optimised for
net9.0with nullable reference types. - Plays nicely with LINQ, async/await, and JSON serialisation out of the box.
- Add the projects you need to your solution (project references today, NuGet packages when published).
- Restore and build:
dotnet restore dotnet build
- Import namespaces:
using RustLikeValues.RustLikeOption; using RustLikeValues.RustLikeResult; using RustLikeValues.RustLikeExtension;
var maybePort = Option.TryCreate(() => int.Parse(Environment.GetEnvironmentVariable("PORT")));
var port = maybePort
.Filter(p => p is >= 1024 and <= 65535)
.UnwrapOr(8080);
Console.WriteLine($"Starting server on port {port}");Key points:
- Construct with
Option.Some(value)orOption.None, or rely on implicit conversions viaToOption(). - Use
Map,MapAsync,AndThen,Filter,Unwrap,UnwrapOr, andMatchfor fluent workflows.
Result<int, string> CalculateTotal(IEnumerable<string> rawValues)
{
return rawValues
.Select(value => Result.Try(() => int.Parse(value)))
.Sequence()
.Map(numbers => numbers.Sum())
.MapErr(ex => ex.Message);
}
var total = CalculateTotal(["10", "20", "30"]).Match(
ok => $"Total: {ok}",
err => $"Failed: {err}"
);
Console.WriteLine(total);Highlights:
- Construct with
Result.Ok(value)/Result.Err(error)or implicit helpers (OkValue,ErrValue). - Compose pipelines with
Map,MapErr,AndThen, async variants,Transpose, andSequence. - Extract values via
Match,Unwrap,UnwrapOr, andUnwrapErrwhen appropriate.
- Collection helpers:
Sequence,FilterMap,FindFirst,FindLast, and dictionaryGetextensions. Result.Trywrapper captures exceptions asResult<T, Exception>.RLogger<T>composes console/file/custom providers and returnsResult<Unit, Exception>so logging failures stay explicit.
Option<T> and Result<T, E> ship with System.Text.Json converters so you can serialise and deserialise them without additional setup.
MIT – see LICENSE if present, or add your preferred license file before distributing.