The scope of the cfr variable. Pluralsight C # test

I am preparing for the microsoft exam about C # 70-483, "still a long way" and after the C # plural. After running the test and checking for my incorrect answers, I came up with this.

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 a variable go out of scope? Answers:

  • When exiting the method ListTowns().

  • Upon exiting foreach loop

  • I never go out of scope because of the method static.

  • Upon exiting for loop

The correct answer is 4, but my answer is 2. Because after the for u loop, you can still use i. Or is my definition of β€œout of scope” incorrect?

+4
source share
2 answers

. # , " ", , i - foreach, for foreach. # 5 3.7:

, (Β§8.5.1), , . foreach.

,

Console.WriteLine(i);

for , . foreach i, foreach, i . ( - , .)

, , , . Pluralsight, .

+8

2 .

Visual Studio

class Program
{
    static void Main(string[] args)
    {
         string[] testdata = { "one", "two", "three", "four"};
         ListCheckFunction(testdata);
         Console.ReadLine();
    }

    static void ListCheckFunction(string[] countries)
    {
        foreach (string country in countries)
        {
            int townCount = countries.Count();
            int i = 0;
            for (i = 0; i < townCount; i++)
            {
                Console.WriteLine(country + " " +i);
            }
            Console.WriteLine(i + " i is still in scope");
        }
    }
}

one 0
one 1
one 2
one 3
4 i is still in scope
two 0
two 1
two 2
two 3
4 i is still in scope
three 0
three 1
three 2
three 3
4 i is still in scope
four 0
four 1
four 2
four 3
4 i is still in scope
0

Source: https://habr.com/ru/post/1671235/


All Articles