System.Collections.IEnumerable

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.


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:IEnumerable 
{
   private MyObject[] _myobjects;

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

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

public class MyObjectsEnum : 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)
{
}


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