#1,119 – Scope of Iteration Variable Is Limited to Body of foreach

The iteration variable that is set to a new element during each pass of a foreach statement only has scope within the body of the foreach loop.  It may not be used or referenced outside of the loop.

            List<Dog> myDogs = new List<Dog>
                {
                    new Dog {Name = "Kirby", Age = 15},
                    new Dog {Name = "Ruby", Age = 2},
                    new Dog {Name = "Jack", Age = 17}
                };

            foreach (Dog d in myDogs)
            {
                Console.WriteLine(d);
                d.Age++;
            }

            // Compile Error: The name 'd' does not exist in the current context
            string someDog = d.Name;
Advertisements

#1,115 – Iterating Through a Collection Using the foreach Statement

In the same way that you can iterate through an array using foreach, you can iterate through the elements of a collection one at a time.  You do this by writing a loop–a block of code that is executed more than once, executing once for each element in the collection. This is done using the C# foreach statement.

The foreach statement declares a variable local to the loop of the same type of the elements in the collection.  This variable takes on the value of each element in the collection.

            List<Dog> myDogs = new List<Dog>
            {
                new Dog {Name = "Kirby", Age = 15},
                new Dog {Name = "Jack", Age = 17},
                new Dog {Name = "Ruby", Age = 2}
            };

            // Output using overridden ToString() method
            foreach (Dog d in myDogs)
                Console.WriteLine(d);
1115-001

#986 – Using goto to Jump to a Label

You can use the goto statement within a block of code to explicitly jump to another location in the code using a label.

            Dog d = new Dog("Bob", 5);

        DoTraining:
            // Train my dog
            d.Train();
            if (d.NumMinutesCanSit < 5)
                goto DoTraining;

            Console.WriteLine("My dog is trained!");

While you can use a goto statement to jump to a label, it’s almost always a bad idea to use goto in this way.  You can always use structured programming techniques, like the while statement, rather than goto.  Code containing goto statements is typically harder to understand than functionally equivalent code written using structured programming constructs.

Here’s the above block of code, re-written to use a while loop.

            do
                d.Train();
            while (d.NumMinutesCanSit < 5);

#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";

            Console.WriteLine(name);
        }

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

            if (DateTime.Now.DayOfWeek == DayOfWeek.Wednesday)
            {
                string bestFood = "Pizza";
                Console.WriteLine(bestFood);
            }

            // 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");

963-001