System.Collections.IEnumerable

Added in .NET 1.1
This is the minimum functionality and just lets you traverse in a forward direction.
This interface defines GetEnumerator method which is used to provide the foreach and forloop statements
All the standard collection types (array, arraylist, sortedlist etc) all implement this interface
This is why you an use the foreach statement with any of these types.


public interface IEnumerable 
{
   IEnumerator GetEnumerator();
}

Standard Collection - Array
Arrays implement this interface

int[] array1 = new int[] {0,1,2,3,4,}; 

foreach (int item in array1)
{
   System.Console.WriteLine(item);
}

for (int 1 =0; I < array1.Length; i++)
{
   System.Console.WriteLine(array1[i]);
}


public class MyObject 
{
{

public class MyObjects : System.Collections.IEnumerable 
{
   private MyObject[] _myobjects;

   IEnumerator IEnumerable.GetEnumerator():
   {
      return (IEnumerator)GetEnumerator()
   }

   public MyObjectsEnum GetEnumerator()
   {
      return new MyObjectsEnum (_myobjects);
   }
}

public class MyObjectsEnum : System.Collections.IEnumerator
{
   public MyObject[] _myobjects;
   int position = -1;

   public MyObjectsEnum (MyObject[] myobjects)
   {
      _myobjects = myobjects;
   }

   public bool MoveNext()
   {
      position ++;
      return (position < _myobjects.Lengths);
   }

   public void Reset()
   {
      position ++;
      return (position < _myobjects.Length);
   }

   object IEnumerator.Current
   {
      get
      {
         return Current;
      }
   }

   public myObject Current
   {
      get
         {
            try
            {
               return _MyObjects[position];
            }
            catch (IndexOutOfRangeException)
            {
               throw new InvalidOperationException();
            }
       }
    }
}

MyObjects ListOfObjects = new MyObjects()
for each (myobject obj in ListOfObjects)
{
}

The "string" data type implements IEnumerable automatically
Which means we can use foreach

string s = "Better"; 
foreach (char c in s)
{
   Console.Write(c + "-");
}

replaces

string s = "Better"; 
IEnumerator myENumerator = s.GetENumerator();
while (myENumerator.MoveNext())
{
   char c = (char)myEnumerator.Current;
   Console.Write(c + "-");
}
// Output "B-e-t-t-e-r"


© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrevNext