Scope of a variable cfr. Pluralsight C# test

I'm preparing for my microsoft exam about c# 70-483, "still a long way to go" and following the C# path on pluralsight. After doing the test and review my incorrect answers i came up to this one.

2.Consider the following code:

static void ListTowns(string[] countries)
 {
    foreach (string country in countries)
    {
        int townCount = GetTownCount(country);
        int i = 0;
        for (i = 0; i < townCount; i++)
        {
            Console.WriteLine(GetTownName(country, i));
        }
    } 
}

When does the variable i go out of scope? Answers:

  1. On exiting the ListTowns() method.

  2. On exiting the foreach loop

  3. I never goes out of scope because the method is static.

  4. On exiting the for loop

The Correct answer is 4, But my answer is 2. Because after the for loop u still can use i. Or is my definition of "out of scope" not correct?

Jon Skeet
people
quotationmark

The question is vague and badly worded IMO. There's no such concept as a variable "going out of scope" in C# - but there is the scope of a variable, and the scope of the i variable is the whole of the foreach loop body, including the empty set of statements between the closing brace of the for loop and the closing brace of the foreach loop. The relevant part of the C# 5 specification is 3.7:

The scope of a local variable declared in a local-variable-declaration (ยง8.5.1) is the block in which the declaration occurs. In this case, the block is the block of the foreach loop.

The fact that you can write

Console.WriteLine(i);

after the for loop and it still compiles shows it's still in scope. Each iteration of the foreach loop uses a different i variable, but everywhere within the foreach loop, i is in scope. (That's true even before its declaration - you can't use it, but it's still in scope.)

I'd have given the same answer as you, as the best approximation to what's being asked. I suggest you email Pluralsight to ask them to improve the question.

people

See more on this question at Stackoverflow