#964 – Declaring a Variable within a Block of Statements

When you declare a block of statements in your code, you can declare variables within that block that will have a scope that is local to the block.  This is, the variable will be visible only to other code within the block.

This is most often done within a function:

        static void DoSomething()
            // Variable local to this function
            string name = "Bob";


You can, however, declare local variables within any block of statements.

            if (DateTime.Now.DayOfWeek == DayOfWeek.Wednesday)
                string bestFood = "Pizza";

            // Can't access bestFood variable out here

#963 – Use Braces to Enclose a Block of Statements

block of statements in C# is a series of individual statements enclosed by a set of curly braces ({, }).  You can typically include a block of statements wherever a single statement is expected.

            // Single statement follows if
            if (DateTime.Now.DayOfWeek == DayOfWeek.Monday)
                Console.WriteLine("Getting to work");

            // Block of statements follows if
            if (DateTime.Now.DayOfWeek == DayOfWeek.Saturday)
                Console.WriteLine("Making pancakes");
                Console.WriteLine("Washing my socks");
                Console.WriteLine("Mowing the lawn");

Although far less common, you can also include a block of statements to arbitrarily group a set of statements within a longer sequence of statements.

            Console.WriteLine("Reading Edith Wharton");

                Console.WriteLine("Eating lunch");
                Console.WriteLine("Washing my hands");

            Console.WriteLine("Studying Byzantium");