0%

Either

install-package T1.Standard

Instead of using exceptions extensively, we should use Either as a replacement.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public Result SayHello(string name)
{
if( name == "hack" ) {
throw new Exception("Bad Request");
}
return new Result
{
ErrorMessage = string.Empty
};
}

try {
return SayHello("xxxx");
} catch (Exception e1) {
return new Result {
ErrorMessage = e1.Message
};
}

This is a C# implementation of the “Either” type. The Either type is a functional programming concept that allows you to represent values that can be one of two types, “left” or “right”.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public Either<Result, Exception> SayHello(string name)
{
if( name == "hack" ) {
return new Either<Result, Exception>(new Exception("Bad Request"));
}
return new Either<Result, Exception>(new Result
{
ErrorMessage = $"Hi {name}"
});
}

return SayHello("xxx").Match(
result => result,
ex => new Result {
ErrorMessage = string.Empty,
}
);