#710 – Variables Declared in a Block Aren’t Visible Outside of the Block

If you declare a variable within a code block, that variable is usable only within the scope of that block.  It is not visible and can’t be referenced outside of the block.

        static void Main(string[] args)
        {
            for (int i = 0; i < 5; i++)
            {
                string promise = "I will not pull my sister's pigtails";
                Console.WriteLine(promise);
            }

            // Compile-time Error: The name 'promise' does not exist in the current context
            Console.WriteLine(promise);
        }

Advertisement