Erro do Compilador CS1579

A instrução foreach não pode operar em variáveis do tipo 'type1', pois 'type2' não contém uma definição pública para 'identifier'

Para iterar por meio de uma coleção usando a instrução foreach, a coleção deve atender aos seguintes requisitos:

  • O tipo deve incluir um método GetEnumerator público sem parâmetros, cujo tipo de retorno é um tipo de classe, estrutura ou interface.
  • O tipo de retorno do método GetEnumerator deve conter uma propriedade pública denominada Current e um método público sem parâmetros denominado MoveNext, cujo tipo de retorno é Boolean.

Exemplo

O exemplo a seguir gera CS1579 porque a classe MyCollection não contém o método público GetEnumerator:

// CS1579.cs  
using System;  
public class MyCollection
{  
   int[] items;  
   public MyCollection()
   {  
      items = new int[5] {12, 44, 33, 2, 50};  
   }  
  
   // Delete the following line to resolve.  
   MyEnumerator GetEnumerator()  
  
   // Uncomment the following line to resolve:  
   // 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.Length);  
      }  
  
      public int Current => collection.items[nIndex];
   }  
  
   public static void Main()
   {  
      MyCollection col = new MyCollection();  
      Console.WriteLine("Values in the collection are:");  
      foreach (int i in col)   // CS1579  
      {  
         Console.WriteLine(i);  
      }  
   }  
}