A .NET library which provides a Result type for representing the outcome of operations in C#.
Louis Seubert
165e0c5c26
Remove the async naming rule as the tooling does not really work out to detecting the right usage of the `Async` suffix. |
||
---|---|---|
.forgejo/workflows | ||
src | ||
.editorconfig | ||
.gitignore | ||
Directory.Build.props | ||
Directory.Build.targets | ||
Directory.Packages.props | ||
Geekeey.Extensions.Result.sln | ||
global.json | ||
LICENSE.md | ||
nuget.config | ||
README.md |
Geekeey.Extensions.Result
A .NET library provides a Result type for representing the outcome of operations in C#. It offers a clean and concise way to handle success and failure scenarios, promoting better error handling and code readability.
Features
- Success and Failure States: Represent successful outcomes with a value (
Prelude.Success()
) or failures with an error (Prelude.Failure()
). - Immutability:
Result<T>
objects are immutable, ensuring thread safety and preventing accidental modification. - Chaining Operations: Methods like
Map
andThen
allow for chaining operations on successful results, promoting a functional programming style.
Getting Started
Install the NuGet package:
dotnet add package Geekeey.Extensions.Result
You may need to add our NuGet Feed to your nuget.config
this can be done by adding the following lines
<packageSources>
<add key="geekeey" value="https://git.geekeey.de/api/packages/geekeey/nuget/index.json" />
</packageSources>
Configure
The package adds a global using for the functions in the Prelude
class when the ImplicitUsings
is enabled in
the .csproj
file. This global using is recommended but can also be removed, by removing
the Geekeey.Extensions.Result.Prelude
value from the item group <Usings>
. For more information about that see
the Project.props
file inside the project tree.
Usage
public Result<int> Divide(int dividend, int divisor)
{
if (divisor == 0)
{
return Prelude.Failure<int>("Division by zero");
}
return Prelude.Success(dividend / divisor);
}
if (result.IsSuccess)
{
Console.WriteLine("Result: " + result.Value);
}
else
{
Console.WriteLine("Error: " + result.Error);
}
_ = await Prelude.Try(() => File.ReadAllLines("i_do_not_exist.txt"))
.ThenAsync(static async Task<Result<IReadOnlyList<int>>> (list) =>
{
using var client = new HttpClient();
Task<Result<int>> DoSomeThing(string line)
=> Prelude.TryAsync(() => client.GetAsync(line))
.Map(static async response => int.Parse(await response.Content.ReadAsStringAsync()));
var results = await Task.WhenAll(list.Select(DoSomeThing).ToArray());
return results.Join();
});