Result Type
Result<R> is similar to std::result data type in Rust programming language and allows to handle method call errors without try-catch
block. The value can contain actual result returned from method or error in the form of exception.
.NET library provides TryInvoke
extension methods to return Result<T>
from popular delegate types such as Func, Converter. The type behaves like monad and the pipeline of calls can be constructed.
using DotNext;
Func<string, int> parser = int.Parse;
Result<int> result = parser.TryInvoke("42");
if(result) //successful
{
var i = (int) result;
}
else
{
throw result.Error;
}
This type is paired with Optional data type. Result<T>
can be converted to it implicitly. But conversion loses information about exception:
using DotNext;
Func<string, int> parser = int.Parse;
int result = parser.TryInvoke("42").OrInvoke(error => 0);