Information
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.

Using foreach with Collections

Visual Studio .NET 2003

To iterate through a collection, the collection must meet specific requirements. For example, in the following foreach statement:

   foreach (ItemType item in myCollection)

myCollection must meet the following requirements:

  • The collection type:
    • Must be one of the types: interface, class, or struct.
    • Must include an instance method named GetEnumerator that returns a type, for example, Enumerator (explained below).
  • The type Enumerator (a class or struct) must contain:
    • A property named Current that returns ItemType or a type that can be converted to it. The property accessor returns the current element of the collection.
    • A bool method, named MoveNext, that increments the item counter and returns true if there are more items in the collection.

There are three approaches to using collections:

  1. Create a collection using the above instructions. This collection can only be used in a C# program.
  2. Create a generic collection using the above instructions, in addition to implementing the IEnumerable interface. This collection can be used from other languages such as Visual Basic.
  3. Use one of the predefined collections in the collection classes.

The following examples demonstrate the three approaches.

Example Demonstrates Comment
Example 1 A C#-specific collection. This example creates a collection by using the instructions above.
Example 2a A generic collection. This example creates a collection by using the instructions above and implements the IEnumerable and IEnumerator interfaces.
Example 2b A generic collection with a Dispose method. Same as Example 2a except that a user-defined enumerator inherits from IDisposable and implements a Dispose method.
Example 3 Using one of the predefined collection classes. This example creates a Hashtable instance and uses the Hashtable class members to manipulate the collection. The Hashtable class represents a dictionary of associated keys and values, implemented as a hash table.

For more information on the interfaces IEnumerator and IEnumerable, and the Hashtable class, see the System.Collections section in the .NET Framework SDK.

Example 1

// statements_foreach_collections.cs
// Using foreach with C#-specific collections:
using System;

// Declare the collection:
public class MyCollection 
{
   int[] items;

   public MyCollection() 
   {
      items = new int[5] {12, 44, 33, 2, 50};
   }

   public MyEnumerator GetEnumerator() 
   {
      return new MyEnumerator(this);
   }

   // Declare the enumerator class:
   public class MyEnumerator 
   {
      int nIndex;
      MyCollection collection;
      public MyEnumerator(MyCollection coll) 
      {
         collection = coll;
         nIndex = -1;
      }

      public bool MoveNext() 
      {
         nIndex++;
         return(nIndex < collection.items.GetLength(0));
      }

      public int Current 
      {
         get 
         {
            return(collection.items[nIndex]);
         }
      }
   }
}

public class MainClass 
{
   public static void Main() 
   {
      MyCollection col = new MyCollection();
      Console.WriteLine("Values in the collection are:");

      // Display collection items:
      foreach (int i in col) 
      {
         Console.WriteLine(i);
      }
   }
}

Output

Values in the collection are:
12
44
33
2
50

Example 2a

This example repeats the same algorithm of Example 1, but uses a generic collection that can be enumerated from other languages such as Visual Basic. This type of collection must implement the IEnumerable interface from the System.Collections namespace.

// statements_foreach_generic_collection.cs
// Using foreach with a generic collection
using System;
using System.Collections;

// Declare the collection and implement the IEnumerable interface:
public class MyCollection: IEnumerable 
{
   int[] items;
   public MyCollection() 
   {
      items = new int[5] {12, 44, 33, 2, 50};
   }

   public MyEnumerator GetEnumerator() 
   {
      return new MyEnumerator(this);
   }

   // Implement the GetEnumerator() method:
   IEnumerator IEnumerable.GetEnumerator() 
   {
      return GetEnumerator();
   }

   // Declare the enumerator and implement the IEnumerator interface:
   public class MyEnumerator: IEnumerator 
   {
      int nIndex;
      MyCollection collection;
      public MyEnumerator(MyCollection coll) 
      {
         collection = coll;
         nIndex = -1;
      }

      public void Reset() 
      {
         nIndex = -1;
      }

      public bool MoveNext() {
         nIndex++;
         return(nIndex < collection.items.GetLength(0));
      }

      public int Current 
      {
         get 
         {
            return(collection.items[nIndex]);
         }
      }

      // The current property on the IEnumerator interface:
      object IEnumerator.Current 
      {
         get 
         {
            return(Current);
         }
      }
   }
}

public class MainClass 
{
   public static void Main(string [] args) 
   {
      MyCollection col = new MyCollection();
      Console.WriteLine("Values in the collection are:");

      // Display collection items:
      foreach (int i in col) 
      {
         Console.WriteLine(i);
      }
   }
}

Output

Values in the collection are:
12
44
33
2
50

Example 2b

This example is the same as Example 2a except that it also implements a Dispose method. Dispose is implemented in a user-defined enumerator that inherits from IDisposable.

The foreach statement provides support for disposable enumerators. If an enumerator implements the IDisposable interface, the foreach statement guarantees that the Dispose method is called on the enumerator no matter how the enumeration loop is terminated.

// statements_foreach_generic_collection2.cs
// Using foreach with a generic collection
using System;
using System.Collections;

// Declare the collection and implement the IEnumerable interface:
public class MyCollection: IEnumerable 
{
   int[] items;
   public MyCollection() 
   {
      items = new int[5] {12, 44, 33, 2, 50};
   }

   public MyEnumerator GetEnumerator() 
   {
      return new MyEnumerator(this);
   }

   // Implement the GetEnumerator() method:
   IEnumerator IEnumerable.GetEnumerator() 
   {
      return GetEnumerator();
   }

   // Declare the enumerator and implement the IEnumerator 
   // and IDisposable interfaces
   public class MyEnumerator: IEnumerator, IDisposable
   {
      int nIndex;
      MyCollection collection;
      public MyEnumerator(MyCollection coll) 
      {
         collection = coll;
         nIndex = -1;
      }

      public void Reset() 
      {
         nIndex = -1;
      }

      public bool MoveNext()
      {
         nIndex++;
         return (nIndex < collection.items.GetLength(0));
      }

      public int Current 
      {
         get 
         {
            return (collection.items[nIndex]);
         }
      }

      // The current property on the IEnumerator interface:
      object IEnumerator.Current 
      {
         get 
         {
            return (Current);
         }
      }
   
      public void Dispose()
      {
         Console.WriteLine("In Dispose");
         collection = null;
      }
   }
}

public class MainClass 
{
   public static void Main(string [] args) 
   {
      MyCollection col = new MyCollection();
      Console.WriteLine("Values in the collection are:");

      // Display collection items:
      foreach (int i in col) 
      {
         Console.WriteLine(i);
      }
   }
}

Output

Values in the collection are:
12
44
33
2
50
In Dispose

Example 3

In this example, the predefined Hashtable collection class is used. By using the System.Collections namespace in your program, you can have access to the Hashtable class and its members. To add entries to the Hashtable object, use the Add method.

// statements_foreach_hashtable.cs
// Using the Hashtable collection class
using System;
using System.Collections;
public class MainClass 
{
   public static void Main(string [] args) 
   {
      // Declare a Hashtable object:
      Hashtable ziphash = new Hashtable();

      // Add entries using the Add() method:
      ziphash.Add("98008", "Bellevue");
      ziphash.Add("98052", "Redmond");
      ziphash.Add("98201", "Everett");
      ziphash.Add("98101", "Seattle");
      ziphash.Add("98371", "Puyallup");

      // Display contents:
      Console.WriteLine("Zip code       City");
      foreach (string zip in ziphash.Keys) 
      {
         Console.WriteLine(zip + "          " + ziphash[zip]);
      }
   }
}

Output

Zip code       City
98201          Everett
98052          Redmond
98101          Seattle
98008          Bellevue
98371          Puyallup

See Also

foreach, in | Collection Classes Tutorial | Using foreach with Arrays

Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft