I have another fairly unimportant theory question but I was hoping to find clarity on this anyhow. As per a text book I have, it states the the following code should have different results from C# version 4 to C# version 5:
static void Main(string[] args)
{
var values = new List<int> { 10, 20, 30 };
var funcs = new List<Func<int>>();
foreach (var value in values)
{
funcs.Add(() => value);
}
foreach(var f in funcs)
{
Console.WriteLine((f()));
}
Console.ReadKey();
}
According to the material I have, in C# version 4, 30 should be written to the console 3 times due to the following:
With C# 4 the compiler defines the loop variable outside of the while loop and reuses it with every iteration. Thus, at the end of the loop the variable has the value from the last iteration.
And in C# 5, the values 10, 20, 30 should be written to the console however, despite changing the C# version (I'm definitely changing the language version and not the .NET framework (although I've tried that as well)) both version write 10, 20, 30 to the console.
I realize this isn't very important but I'm just wondering why this is as it might be something I'm doing wrong and could influence other tests that I try between language versions of C#.
The devil is in the details - as you correctly quoted, the old behavior only occurs in the C# 4 compiler, not the language or framework itself.
As such, all depends on what environment (i.e. Visual Studio) you use to compile the code, regardless of language compatibility level or target framework version chosen.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With