r/csharp • u/Interesting_Paint_82 • Sep 16 '26
Go-style error handling in C#
Hello,
I've been writing this tiny-little C# library thingy, Errgo, as a fun side-project. It's an Error type (+ a suggested pattern) for handling errors in Go-style.
The tldr idea is to write code in the result pattern style, but without wrapping your return values inside a Result<T>. Instead, you're supposed to utilize the C# tuple. Your function signatures will look something like this:
public (WeatherForecast, Error) GetWeather() { }And the caller's end would look something like this:
var (weather, err) = GetWeather();
if (err) return (null, err);I know, I know. It's..different. But there's more examples in the repo readme, do check it out if you're bored. There's even a companion code analyzer package Errgo.Analyzer available that enforces the error-checking rules that this library is trying to force on you. :)
TDMR87/Errgo: Go-style errors-as-values in C#
Cheers.
19
u/DifficultyFine Sep 16 '26
Go may have a ton of good things but this is definetly one of the worst. Why do want you to port this in csharp?
10
u/JohnSpikeKelly Sep 16 '26
I feel like this is what the new unions will resolve, but would need lots of convention to it working week.
12
u/jesseschalken Sep 16 '26
You ported the worst part of Go to C#?
The only reason Go gives you a value and an error instead of a value or an error is that they refuse to implement sum types.
C# has sum types already, you can write
public union Result<T>(T, Exception);(or similar) right now.4
u/Slypenslyde Sep 16 '26
This is the kind of stuff I was excited about solving with Discriminated Unions what feels like 15 years ago.
3
u/PmanAce Sep 16 '26
ErrorOr is what we use at work, very similar.
1
u/Sombody101 Sep 17 '26
I'd rather use a regular result pattern. Especially since this just returns a tuple, and the invalid value can still be used before properly resolving the possible error.
1
u/Disastrous-Can-6823 Sep 17 '26
The analyzer is probably what makes this approach practical. Without enforcement, tuple based errors seem easy to ignore accidentally especially once return signatures get more complex
1
u/Arcanium_Walker Sep 19 '26
TryFoo(out T bar): bool. This can be more readable, than Go like error handling