-
Notifications
You must be signed in to change notification settings - Fork 8
/
VariableFromContainingMethod.cs
95 lines (83 loc) · 2.6 KB
/
VariableFromContainingMethod.cs
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
92
93
94
95
namespace AnonymousFunctions;
public static class VariableFromContainingMethod
{
public static Predicate<int> IsGreaterThan(int threshold)
{
return value => value > threshold;
}
// This example illustrates what the compiler generates, but since it includes
// 'unspeakable' names, it can't compile, hence the #if false
#if false
[CompilerGenerated]
private sealed class <>c__DisplayClass1_0
{
public int threshold;
public bool <IsGreaterThan>b__0(int value)
{
return (value > this.threshold);
}
}
#endif
static void Calculate(int[] nums)
{
int zeroCount = 0;
int[] nonZeroNums = Array.FindAll(
nums,
v =>
{
if (v == 0)
{
zeroCount += 1;
return false;
}
else
{
return true;
}
});
Console.WriteLine($"Number of zero entries: {zeroCount}");
Console.WriteLine($"First non-zero entry: {nonZeroNums[0]}");
}
public static void PrematureDisposal()
{
HttpClient http = GetHttpClient();
using (FileStream file = File.OpenWrite(@"c:\temp\page.txt"))
{
http.GetStreamAsync("https://endjin.com/")
.ContinueWith((Task<Stream> t) => t.Result.CopyToAsync(file));
} // Will probably dispose FileStream before callback runs
}
private static HttpClient GetHttpClient() => new();
public static void Caught()
{
var greaterThanN = new Predicate<int>[10];
for (int i = 0; i < greaterThanN.Length; ++i)
{
greaterThanN[i] = value => value > i; // Bad use of i
}
Console.WriteLine(greaterThanN[5](20));
Console.WriteLine(greaterThanN[5](6));
}
public static void FixedCaught()
{
var greaterThanN = new Predicate<int>[10];
for (int i = 0; i < greaterThanN.Length; ++i)
{
int current = i;
greaterThanN[i] = value => value > current;
}
Console.WriteLine(greaterThanN[5](20));
Console.WriteLine(greaterThanN[5](6));
}
public static void CaptureAtMultipleScopes()
{
var greaterThanN = new Predicate<int>[10];
int offset = 10;
for (int i = 0; i < greaterThanN.Length; ++i)
{
int current = i;
greaterThanN[i] = value => value > (current + offset);
}
}
public static Predicate<int> IsGreaterThan10() => static value => value > 10;
}