Welcome to my tutorial on Looping Structures in C#, this tutorial was written do to the number of times I, and other programmers, are asked about various loops, and how to perform one. In this tutorial I will demonstrate how to 4 main looping structures work, those loops are:

  • For loop
  • For Each loop
  • While loop
  • Do-While loop


Though this tutorial is for demonstrating how the different looping structures work, you will get a small ntroduction to the System.IO Namespace because in our examples we will be using the DirectoryInfo Class and the FileInfo Class.

You will also get a small introduction to using Properties and the OO (Object Orientated) way of programming as all the logic in this tutorial is in its own class, thus separating logic from presentation, which is all the Form should handle, thus giving an n-tier architecture, which is the whole dea behind the .Net way or programming.

Looping structures, though one of the most basic items in programming, no matter the language, are very important as they allow us to:

  • Run a particular block of code, even when we don't know how many times it needs to be ran.
  • Iterate through the items in a collection, like an Array or a Generic List of items.
  • Allow us to execute a block of code a set number of times.


The first thing we need in our class is to ensure we import the proper Namespaces for the class. For this class the Namespaces needed are:


CODE

using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using System.IO;



The next thing we will look at, since I said there would be a small introduction to using properties, we need variables that will be used for populating and retrieving the property's value. In this class, since this is an introduction tutorial, we will have only 2 properties. One of these properties is a Read/Write property, meaning the value is set outside the class, normally in your form code, the other is a ReadOnly property, meaning nothing outside our class can write to the value, it can only read it's value. First the private variables for our properties:


CODE

#region Variables
/// <summary>
/// property variable to hold the directory to
/// retrieve the file names from
/// </summary>
private DirectoryInfo _dir;

/// <summary>
/// property variable for our ReadOnly property
/// which will hold the success status of our
/// methods.
/// </summary>
private bool _status;
#endregion



NOTE: When programming it is a good idea to enclose separate sections of your code in #region tags. This helps separate different sections, thus making it easier to find blocks of code based on its region.

Next we will look at the properties themselves. The first, Directory is a read/write property as explained above, so its value is set outside the class. To make a property read only, like our Status property, you have just a get and leave out the set like you would have in a read/write property:


CODE

#region Properties
    #region Read/Write Properties
    /// <summary>
    /// property to hold the directory we're going to loop through
    /// </summary>
    public DirectoryInfo Directory
    {
        get { return _dir; }
        set { _dir = value; }
    }
    #endregion

    #region ReadOnly Properties
    /// <summary>
    /// ReadOnly property to hold the status of the operation
    /// we will use this to let the user know if the process
    /// failed or was successful
    /// </summary>
    public bool Status
    {
        get { return _status; }
    }
    #endregion
#endregion



The next item you need in your class is at least one Constructor. The constructors allow us to instantiate our class so we can access it's properties, methods and events. Constructors also allow us to instantiate class variables thus preventing a NullReferenceException.

In this class we have a single constructor which we use to instantiate our 2 property variables, our constructor looks like:


CODE

#region Constructors
/// <summary>
/// Class constructure, used to instantiate our property
/// variables. This prevents a NullReferenceException from
/// happening when we call a method in our class file
/// </summary>
public LoopingStructures()
{
    _dir = null;
    _status = false;
}
#endregion



Now that we have the necessities out of the way, we can start looking at how the different looping structors work, and the syntax for creating them. So now lets jump right into the 4 different loops.


Foreach Loop

The foreach loop is great for accessing each element in a collection, for example, accessing each number in an integer array or each item in a list. The syntax for a Foreach loop is:


QUOTE

foreach (<type> <variable> in <collection>)
{

}


In our foreach loop we will be looping through all the files in the directory provided. This value will come from the value provided to our Directory Property. We will then populate our generic list with the names of each file in the directory. Lets take a look at our foreach loop:


CODE

#region RetrieveFilesWithForEachLoop
/// <summary>
/// Method for retrieving all the files for the given directory. In this
/// method we'll be taking a look at the foreach loop. We will use a foreach
/// loop to loop through all the files in the given directory and populate
/// our Generic list.
/// </summary>
/// <returns></returns>
public List<string> RetrieveFilesWithForEachLoop()
{
    //variable to hold the returning value, the
    //list of file names in the provided directory
    List<string> files = new List<string>();
    //here we'll use a try...catch to catch any exceptions,
    //and also to catch the exception we're going to
    //throw if the directory isnt found
    try
    {
        //first make sure the directory exists
        if (System.IO.Directory.Exists(_dir.ToString()))
        {
            //now the foreach loop. We will loop through
            //all the files in the directory and retrieve
            //their names
            foreach (FileInfo file in _dir.GetFiles())
            {
                //add each file to the Generic list
                files.Add(file.Name.ToString());
            }
            _status = true;
        }
        else
        {
            _status = false;
            files = null;
            throw new DirectoryNotFoundException("The directory " + _dir.ToString() + " could not be found.");
        }
    }
    catch (Exception ex)
    {
        files = null;
        _status = false;
        System.Windows.Forms.MessageBox.Show(ex.Message);

    }
    return files;
}
#endregion



As you can see, we first check to make sure the directory exists, if it does then we use the foreach to loop through all the files and retrieve their names and add it to our list, otherwise we throw a DirectoryNotFoundException.


For Loop

The for loop will run a specific number of times, it will initialize a variable to a certain value, and it will increment this variable until it reaches a specified value.

The syntax for a for loop looks like:


QUOTE

for (initialize variable; boolean expression to continue loop; increment variable)
{

}



With our for loop, as with the rest of the loops in this tutorial, we will be using them to count the number of files in the given directory. Now I know there are probably better ways to accomplish this task, but Im simply using that task to show how each loop works. So now lets look at our for loop:


CODE

#region CountFilesWithForLoop
/// <summary>
/// method for counting the number of files in a given
/// directory. In this method we'll be taking a look at
/// the for loop. We will loop through the number of files
/// and increment our counter by 1 for each file in the
/// directory. There are other ways of doing this, but
/// I want to demonstrate the for loop.
/// </summary>
/// <returns></returns>
public int CountFilesWithForLoop()
{
    //create a variable to hold our file counter
    int totalFiles = 0;
    //use a try..catch to catch any exceptions, and
    //to catch the exception we're going to throw if
    //the directory provided doesnt exist
    try
    {
        //check to see if the directory exists, if it
        //doesnt then we'll throw a DirectoryNotFound
        //exception
        if (System.IO.Directory.Exists(_dir.ToString()))
        {
            //now we'll use the for loop to count the number
            //of files in a given directory
            for (int i = 0;i< _dir.GetFiles().Length; i++)
            {
                totalFiles += 1;
            }
        }
        else
        {
            totalFiles = 0;
            _status = false;
            throw new DirectoryNotFoundException("The directory " + _dir.ToString() + " could not be found.");
        }
    }
    catch (Exception ex)
    {
        totalFiles = 0;
        _status = false;
        System.Windows.Forms.MessageBox.Show(ex.Message);
    }
    return totalFiles;
}
#endregion



As with the foreach loop (and the rest of our loops) we first check to ensure the directory exists, if it does them we loop through each file, and on each iteration we increment a variable we named totalFiles. Once we have our count we return that value to the calling method. Once again, if the directory doesnt exist, we throw a DirectoryNotFoundException.

NOTE: All the loops in this tutorial, except the foreach loop, do the same thing, they count files, they check if the directory exists, they return a value to the calling method. I chose this method to show how the loops work knowing there are probably a million ways to accomplish this same task.


While and Do-While Loop

The while and do-while loops will run while a certain boolean expression is true. The syntax for the While Loop looks like:


QUOTE

while (boolean expression)
{

}



The syntax for a Do-While loop looks like:


QUOTE

do
{
//do your work/calculations here
} while (boolean expression)




The main difference between the while loop and the do-while loop is that, in the while loop, the expression is immediately checked and if it results in false, the loop won't run at all. The do-while loop, will run the loop 1 time before checking the expression.

First we will look at our While loop, using the same logic as before we will be counting the number of files in a given directory:


CODE

#region CountFilesWithWhileLoop
/// <summary>
/// method for counting the number of files in a given
/// directory. In this method we'll be taking a look at
/// the while loop. We will loop through the number of files
/// and increment our counter by 1 for each file in the
/// directory. There are other ways of doing this, but
/// I want to demonstrate the while loop.
/// </summary>
/// <returns></returns>
public int CountFilesWithWhileLoop()
{
    //create a variable to hold our file counter
    int totalFiles = 0;
    //use a try..catch to catch any exceptions, and
    //to catch the exception we're going to throw if
    //the directory provided doesnt exist
    try
    {
        //check to see if the directory exists, if it
        //doesnt then we'll throw a DirectoryNotFound
        //exception
        if (System.IO.Directory.Exists(_dir.ToString()))
        {
            //now we'll use the for loop to count the number
            //of files in a given directory
            while (totalFiles < _dir.GetFiles().Length)
            {
                totalFiles += 1;
            }
        }
        else
        {
            totalFiles = 0;
            _status = false;
            throw new DirectoryNotFoundException("The directory " + _dir.ToString() + " could not be found.");
        }
    }
    catch (Exception ex)
    {
        totalFiles = 0;
        _status = false;
        System.Windows.Forms.MessageBox.Show(ex.Message);
    }
    return totalFiles;
}
#endregion



Now for the Do-While loop:


CODE

#region CountFilesWithDoWhileLoop
/// <summary>
/// method for counting the number of files in a given
/// directory. In this method we'll be taking a look at
/// the do while loop. We will loop through the number of files
/// and increment our counter by 1 for each file in the
/// directory. There are other ways of doing this, but
/// I want to demonstrate the do while loop.
/// </summary>
/// <returns></returns>
public int CountFilesWithDoWhileLoop()
{
    //create a variable to hold our file counter
    int totalFiles = 0;
    //use a try..catch to catch any exceptions, and
    //to catch the exception we're going to throw if
    //the directory provided doesnt exist
    try
    {
        //check to see if the directory exists, if it
        //doesnt then we'll throw a DirectoryNotFound
        //exception
        if (System.IO.Directory.Exists(_dir.ToString()))
        {
            //now we'll use the for loop to count the number
            //of files in a given directory
            do
            {
                totalFiles += 1;
            } while (totalFiles <= _dir.GetFiles().Length);
        }
        else
        {
            totalFiles = 0;
            _status = false;
            throw new DirectoryNotFoundException("The directory " + _dir.ToString() + " could not be found.");
        }
    }
    catch (Exception ex)
    {
        totalFiles = 0;
        _status = false;
        System.Windows.Forms.MessageBox.Show(ex.Message);
    }
    return totalFiles;
}
#endregion



That is our 4 looping structures in action. As you can see, each one is interchangeable, and can be used for a wide variety of activities, calculations and counting. Seeing them in action you will realize how vital loops are to programming, no matter what language they're used in.

There are two statements that I did not cover in the loops, and those are the break and continue statements. The break statement allows you to exit from a loop prematurely, before the boolean expression becomes false. The continue statement also allows you to alter the processing of a loop but it lets you skip the rest of a loop and go on to the next loop.

Well we have reached the end of this tutorial on Looping Structures in C#, I hope you found this tutorial useful and informative, and I want to thank you for reading.

Happy Coding smile.gif