SunQuest
 
       C#
  Home arrow C# arrow Branching and Looping in C#, Part 2
ASP Free Forums 
.NET  
ASP  
ASP Code  
ASP.NET  
ASP.NET Code  
BrainDump  
C#  
Code Examples  
Database  
Database Code  
IIS  
Microsoft Access  
MS SQL Server  
Visual Basic.NET  
Windows Scripting  
Windows Security  
XML  
ASP Web Hosting  
ASP.NET Web Hosting 
Dedicated Servers 
Actuate Whitepapers 
Moblin 
Windows Web Hosting
 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
C#

Branching and Looping in C#, Part 2
By: Michael Youssef
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 38
    2005-04-19

    Table of Contents:
  • Branching and Looping in C#, Part 2
  • The while Loop
  • The do/while Loop
  • The goto Statement
  • The return statement
  • break and continue statements

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT

    Stay one step ahead of the competition. Evaluate and give feedback on some of the hottest web development tools on the market today. Make your opinion heard! Click Here

    Branching and Looping in C#, Part 2


    (Page 1 of 6 )

    In the first part of this article we discussed if, switch and for statements. In part 2 we will continue our looping statements (while, do/while and foreach) and we will discuss jump statements (break, continue, goto and return).

    foreach statement

    Visual Basic programmers have been accustomed to using the For Each loop for several years to iterate through an array or a collection. C# features a new loop construction that is easy to use and similar to VB's For Each loop; it's the foreach loop. As you know, you can use a for statement to loop over an array or collection, but there are some problems that you may encounter that produce logic errors.

    For example, you may need to iterate through all the elements in an array using the for statement. If you declared the variable of the loop to 1, the first element in the array will not be accessed. Another problem that can occur is that you may forget and step 2 instead of one, or even worse (as in our last example in Part 1), you use a decrement step -- the list of potential problems is pretty long, in fact.

    The C# foreach loop is used to iterate through each and every element in an array or collection, and you don't have to worry about anything. Although it's little slower than the for loop, the C# compiler optimizes foreach if used with arrays. Here is the syntax of the foreach statement:

    foreach(type declaration in collection)
    {
      statement 1;
      statement 2;
      statement 3;
    }

    Let's take an example:

    using System; 
    namespace MyCompany
    {
      public class Loops
      { 
        static void Main(string[] args)
      {
      int[] myArray = {10, 20, 30, 40}; 
     
      foreach(int temp in myArray)
        {
          Console.WriteLine(temp);
        }
        Console.ReadLine(); 
      } 
     }
    }

     
    Compile and run the above code and you will get the following result.

    Note that we have declared a variable of type int inside the foreach loop to hold the current array's element, and this variable is accessible in the statement block. The foreach loop is intelligent, so for each iteration, it updates its local variable with the new element. With foreach you will not manually increase a counter and set a loop, because it will do it for you. The foreach loop comes with a cost also: you can't assign a new value to the array's elements, because they are read-only inside the foreach loop (via the local variable that we use). Modify the last example so it will look like this:

    foreach(int temp in myArray)
    {
      Console.WriteLine(temp);
      temp = 100;
    }

    When you compile the application you will get the following error:

    "Cannot assign to 'temp' because it is read-only."

    If the element is not a primitive type, you can call a method of the object to modify it or update its state. You can use the foreach statement with the built-in collection classes, or with your handmade collection classes, but in this case you need to implement some interfaces that give foreach the methods to use in iteration through the objects. Anyway, this is beyond the scope of this article, so I will defer that until we discuss Data Structure and Collections with C#.

    More C# Articles
    More By Michael Youssef


     

    C# ARTICLES

    - Color Transformation in C# GDI+ Programming
    - Exceptions in C#
    - Overriding versus Overloading
    - Value Types and Reference Types
    - Defining Member and Type Visibility
    - Managing Files in C#
    - Working with Windows Registry in C#
    - Lossless Image Resizing in C#
    - Lossless Image Converting in C#
    - Creating an RSS Feed with ASP.Net Written in...
    - Polymorphism in C#
    - Inheritance in C#
    - C# Events Explained
    - C# Delegates Explained
    - C# StreamReader and StreamWriter Explained





    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 1 hosted by Hostway