#730 – Check for null Before Iterating Using foreach Statement

The foreach statement allows iterating through all items in a collection.

            List<string> dogs = new List<string>();
            dogs.Add("Kirby");
            dogs.Add("Jack");

            foreach (string s in dogs)
                Console.WriteLine(s);

            Console.WriteLine("=> Done");

730-001

If the collection referenced in the foreach statement is empty, the body of the loop does not execute.  No exception is thrown.

            List<string> dogs = new List<string>();

            foreach (string s in dogs)
                Console.WriteLine(s);

            Console.WriteLine("=> Done");

730-002
If the object that refers to the collection is null, a NullReferenceException is thrown.

            List<string> dogs = null;

            foreach (string s in dogs)
                Console.WriteLine(s);

            Console.WriteLine("=> Done");

730-003
Because of this, it’s good practice to check for null before iterating through a collection in a foreach loop.

            if (dogs != null)
                foreach (string s in dogs)
                    Console.WriteLine(s);

#583 – You Can’t Modify the Iterator Variable Within a foreach Loop

The iterator variable within a foreach loop is the variable that takes on the value of each item within the corresponding collection, each time through the loop.

            string[] puppets =
                {"Crow T. Robot", "Howdy Doody", "Kermit",
                 "King Friday XIII", "Lamb Chop"};

            // nextPuppet is the iterator variable
            foreach (string nextPuppet in puppets)
            {
                Console.WriteLine("Puppet: {0}", nextPuppet);
            }

If you try to modify this iterator variable within the loop, however, you’ll get a compile-time error.

foreach (string nextPuppet in puppets)
{
    nextPuppet = "(" + nextPuppet + ")";
    Console.WriteLine("Puppet: {0}", nextPuppet);
}

#556 – Using an Enumerator Explicitly

An enumerator is an object that knows how to move through a sequence of elements.  In C#, the foreach statement provides this same functionality wrapping an enumerator.

You can use an enumerator to iterate through a collection, rather than a foreach statement.  This helps in understanding how enumerators work.

The code fragment below shows iterating through a collection using the foreach statement and then doing the same thing using an enumerator.  (dogs is of type List<Dog>).

            // Using foreach
            foreach (Dog d in dogs)
                Console.WriteLine(d.Name);

            // Using enumerator directly
            List<Dog>.Enumerator dogEnum = dogs.GetEnumerator();
            while (dogEnum.MoveNext())
            {
                Dog d = (Dog)dogEnum.Current;
                Console.WriteLine(d.Name);
            }

The enumerator is an object of type List<T>.Enumerator.  We call a method on the List<T> object to get an instance of its enumerator and then navigate through the list using the MoveNext method.  The Current property returns the object that the enumerator is currently pointing to.

#156 – Using break and continue in foreach Loops

When iterating through array elements using the foreach statement, you can use the break statement to break out of the loop–when break is encountered, control is transferred to the code immediately following the loop and no more array elements will be processed.

            foreach (Person p in folks)
            {
                Console.WriteLine("{0} {1}", p.FirstName, p.LastName);

                // If we find Elvis, stop the presses
                if (p.FirstName == "Elvis")
                    break;
            }

The continue statement, when encountered in a foreach loop, causes control to transfer back to the top of the loop and move on to the next element.

            foreach (Person p in folks)
            {
                // Don't print out info for any Adolfs; move to the next person
                if (p.FirstName == "Adolf")
                    continue;

                Console.WriteLine("{0} {1}", p.FirstName, p.LastName);
            }

#155 – Iterating Through an Array Using the foreach Statement

You can write a loop–a block of code that is executed more than once–that executes once for each element in an array, using the C# foreach statement.

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

            Person[] folks = new Person[4];
        	folks[0] = new Person("Bronte", "Emily");
	        folks[1] = new Person("Bronte", "Charlotte");
	        folks[2] = new Person("Tennyson", "Alfred");
	        folks[3] = new Person("Mailer", "Norman");

            string sLastNameList = "";

            // For each Person in array, dump out name and concatenate last name
            foreach (Person p in folks)
            {
                Console.WriteLine("{0} {1}", p.FirstName, p.LastName);
                sLastNameList += p.LastName;
            }