Compiler Error CS1579

 

Updated: July 20, 2015

For the latest documentation on Visual Studio 2017 RC, see Visual Studio 2017 RC Documentation.

foreach statement cannot operate on variables of type 'type1' because 'type2' does not contain a public definition for 'identifier'

To iterate through a collection using the foreach statement, the collection must meet the following requirements:

In this sample, foreach is not able to iterate through the collection because there is no publicGetEnumerator method in MyCollection.

The following sample generates CS1579.

// 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.GetLength(0));  
      }  
  
      public int Current   
      {  
         get   
         {  
            return(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);  
      }  
   }  
}  

Show: