-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDocFragments.xml
More file actions
91 lines (84 loc) · 2.6 KB
/
DocFragments.xml
File metadata and controls
91 lines (84 loc) · 2.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
<?xml version="1.0" encoding="utf-8"?>
<doc>
<BindExtensionMethods>
<returns>
<list type="bullet">
<item>
<description>
Successful with the transformed value if both the input result and the transformation succeed.
</description>
</item>
<item>
<description>
A failure containing the error from either the original result or from the transformation.
</description>
</item>
</list>
</returns>
<example>
<code>
<![CDATA[
using ZeidLab.ToolBox.Results;
namespace ZeidLab.ToolBox.ExampleProject.ResultExamples
{
public static class BindExampleErrors
{
public static readonly ResultError NotPositive = ResultError.New("Not positive");
public static readonly ResultError NotEven = ResultError.New("Not even");
}
public static class BindExamples
{
// Validate that a number is positive.
private static Result<int> ValidatePositive(int x)
// implicit conversion from int to Result<int>
=> x > 0 ? x : BindExampleErrors.NotPositive;
// Validate that a number is even.
private static Result<int> ValidateEven(int x) =>
// implicit conversion from int to Result<int>
x % 2 == 0 ? x : BindExampleErrors.NotEven;
// Multiply by two asynchronously.
private static async Task<Result<int>> MultiplyByTwoAsync(int x)
{
await Task.Delay(10); // Simulate async work.
// implicit conversion from int to Result<int>
return x * 2;
}
// Try operation: Parse a string to an int.
// implicit conversion and exception handling
private static Try<int> ParseNumber(string input)
=> () => int.Parse(input);
// TryAsync operation: Fetch data asynchronously.
#pragma warning disable AMNF0002
private static TryAsync<string> FetchDataAsync(string data)
#pragma warning restore AMNF0002
=> async () =>
{
await Task.Delay(10); // Simulate async fetch.
return Result.Success(data);
};
public static async Task RunAsync()
{
await FetchDataAsync("258")
.BindAsync(ParseNumber)
.BindAsync(ValidatePositive)
.BindAsync(ValidateEven)
.BindAsync(MultiplyByTwoAsync)
.MatchAsync(
success: (int x) => Console.WriteLine($"Async Success: {x}"),
failure: (ResultError error) => Console.WriteLine($"Async Failure: {error.Message}")
);
ParseNumber("InvalidString")
.Bind(ValidatePositive)
.Bind(x => x % 2 == 0 ? Result.Success(x + 3) : BindExampleErrors.NotEven)
.Match(
success: (int x) => Console.WriteLine($"Async Success: {x}"),
failure: (ResultError error) => Console.WriteLine($"Async Failure: {error.Message}")
);
}
}
}
]]>
</code>
</example>
</BindExtensionMethods>
</doc>