Chapter 7. C# 5 bonus features

 

This chapter covers

  • Changes to variable capture in foreach loops
  • Caller information attributes

If C# had been designed with book authors in mind, this chapter wouldn’t exist, or it’d be a more standard length. I could claim that I wanted to include a very short chapter as a sort of palette cleanser after the dish of asynchrony served by C# 5 and before the sweetness of C# 6, but the reality is that two more changes in C# 5 that need to be covered wouldn’t fit into the async chapters. The first of these isn’t so much a feature as a correction to an earlier mistake in the language design.

7.1. Capturing variables in foreach loops

Before C# 5, foreach loops were described in the language specification as if each loop declared a single iteration variable, which was read-only within the original code but received a different value for each iteration of the loop. For example, in C# 3 a foreach loop over a List<string> like this

foreach (string name in names)
{
    Console.WriteLine(name);
}

would be broadly equivalent to this:

string name;                                  #1
using (var iterator = names.GetEnumerator())  #2
{
    while (iterator.MoveNext())
    {
        name = iterator.Current;              #3
        Console.WriteLine(name);              #4
    }
}

7.2. Caller information attributes

Summary