C#: Variable scope in nested block

A variable in a nested block can access variables declared in the outer block.

Consider the following example.

for (int x = 0; x < 5; x++)
{
    for (int y = 0; y < 3; y++)
    {
        Console.WriteLine(x);
        Console.WriteLine(y);
    }
}

The integer x is declared in the first line and it will be available for both the outer and the inner block.

The integer y is declared in the third line and it will be only available to this inner block.

The inner for loop block is printing out x that is declared in the outer block.  This is ok and running it will not generate an error.

Nested Code Block
using System;

namespace Nested
{
    class Program
    {
        static void Main()
        {
            for (int x = 0; x < 5; x++)
            {
                for (int y = 0; y < 3; y++)
                {
                    Console.WriteLine(x);
                    Console.WriteLine(y);
                }
            }
            Console.ReadLine();
        }
    }
}

nested

Series Navigation<< C#: Variable scope
C#: Scope and declaration space >>