11.3 Looping with the foreach keyword


11.3 Looping with the foreach keyword

C# comes with a new and convenient foreach keyword used for looping. What you can do with foreach , you can do with for (or while ), but foreach is very convenient indeed for certain scenarios. For instance, you do not need to create a temporary loop counter variable to keep track of looping. foreach works only for repeating a bunch of statements (or looping through) once for every element of an array or object collection. [5]

[5] I will cover only using foreach for arrays in this section. You can iterate through a collection type using foreach too, but quite some work has to be done to prepare a class so that you can iterate through it using foreach . This special class has to implement System.Collections.IEnumerable and you need to write codes for the abstract methods declared in this interface.

foreach is only good for retrieving information from the array elements “ you should not attempt to assign values to the array elements. Remember that you do not have a counter variable in the loop (unless you create one yourself “ in which case you would be better off using for instead of foreach ).

This is how array elements are retrieved sequentially from the first to the last using the classic for keyword:

 1:  class TestClass{ 2: 3:    public static void Main(){ 4:      int []array = {11,12,13,14,15}; 5: 6:  for (int i  =  0; i<array.Length; i  ++  )  7:  System.Console.WriteLine(array[i]);  8:    } 9:  } 

Output (as expected):

 c:\expt>test 11 12 13 14 15 

You can do the same thing using foreach like this:

 1:  class TestClass{ 2: 3:    public static void Main(){ 4:      int []array = {11,12,13,14,15}; 5: 6:  foreach (int i in array)  7:  System.Console.WriteLine(i);  8:    } 9:  } 

In the program above, in the foreach loop, i is a local variable (the scope of i is only within the foreach loop) which is automatically assigned the value of the next int element in the array. i is not a loop iteration counter. Of course, the type of i declared in the foreach statement must match the element type stored in the array (or at least the array elements can be implicitly cast into i 's type).

Replacing lines 6 “ 7 with this:

 6:  foreach (  double d  in array) 7:    System.Console.WriteLine(d); 

will work just fine, since an int can be implicitly cast to a double . In each iteration, the array elements (of type int ) are implicitly cast into type double before the first statement of the iteration (line 7) starts. If there is a casting problem, the compiler will complain.

Lines 4 “ 7 have been replaced in the following code fragment to illustrate another example. This time a string array is being dealt with:

 4:  string []array = {"apple","orange","banana","chiku"}; 5: 6:  foreach (string s in array)  7:    System.Console.WriteLine(s); 

If array is null , line 6 will throw a System.NullReferenceException (which, by its name , should suggest that it is the C# equivalent of Java's java.lang.NullPointerException ).

foreach comes with limitations too. The following actions cannot be done without additional workarounds:

  • Since there is no loop counter, you cannot assign values to individual array elements or perform any operation requiring a loop counter.

  • You can only use foreach if you intend to iterate from the first to the last element in the array or collection. You cannot, for example, loop from element 3 to element 5 of the array.

If all you want to do is to retrieve all the values in an array or collection, foreach is clear, clean, and easy to use. Otherwise go back to the classic for loop if you need to perform more complex operations involving a counter, or jump out of the loop prematurely.



From Java to C#. A Developers Guide
From Java to C#: A Developers Guide
ISBN: 0321136225
EAN: 2147483647
Year: 2003
Pages: 221
Authors: Heng Ngee Mok

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net