Member-only story
How to Use a Result Type in .NET
Eliminate NullReferenceExceptions and elevate your error handling with this Result type
One of the minor drawbacks of non-functional programming languages is, that you cannot be 100% sure, that the value you are currently handling is not null, without checking it. Oftentimes, we just implement a Function<T>
and go on using that return type in our code, without checking it for null.
Programming languages like Rust or F# elevate the issue to a kind of Result
type or Option
type. This type reminds you - and kind of enforces you - to first check, if the called function really returned the expected value or null.
In C# however, there is not yet a good solution for this matter. You can use a nullable type and set the Nullable
property to true
in your .csproj file, but this is still missing an important aspect of a result type: The explicitness. When you receive a nullable type in your code, you may only see, that it is nullable by the ?
operator next to it, or due to your IDE reminding you, that you may be handling with a null value.
So now we have the need for a Result
type, that explicitly reminds us to check, if the underlying value was set or not. Now imagine, we receive a Result
that is returned by a failed function. The caller surely wants to know, what…