“ClosureAndVariable” (Solution)

Answer

1
2
Copied!

Explanation

The code is translated into the following form:
1
class DisplayClass
2
{
3
public string startLetter;
4
5
public bool Method1(string c)
6
{
7
return c.StartsWith(this.startLetter);
8
}
9
10
public bool Method2(string c)
11
{
12
return c.StartsWith(this.startLetter);
13
}
14
}
15
16
void Main()
17
{
18
DisplayClass displayClass = new DisplayClass();
19
var list1 = new List<string> { "Foo", "Bar", "Baz" };
20
var list2 = list1;
21
displayClass.startLetter = "F";
22
IEnumerable<string> source = list2.Where(displayClass.Method1);
23
displayClass.startLetter = "B";
24
Console.WriteLine(source.Where(displayClass.Method2).Count());
25
}
Copied!
The execution of the LINQ queries will start only in the last line of code. As can be seen, the same helper class creates for both queries. First, the list2.Where(displayClass.Method1) query will be executed. It returns { "Bar", "Baz" } because displayClass.startLetter at the time of execution is "B". Next, the source.Where(displayClass.Method2) query will be executed. It also returns { "Bar", "Baz" }. The number of elements in the result is two.
Problem
Copy link