C# Error CS1579 – foreach statement cannot operate on variables of type ‘{0}’ because ‘{0}’ does not contain a public instance or extension definition for ‘{1}’

C# Error

CS1579 – foreach statement cannot operate on variables of type ‘{0}’ because ‘{0}’ does not contain a public instance or extension definition for ‘{1}’

Reason for the Error & Solution

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 statement, the collection must meet the following requirements:

  • Its type must include a public parameterless GetEnumerator method whose return type is either class, struct, or interface type.
  • The return type of the GetEnumerator method must contain a public property named Current and a public parameterless method named MoveNext whose return type is .

Example

The following sample generates CS1579 because the MyCollection class doesn’t contain the public GetEnumerator method:

// 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);  
      }  
   }  
}  

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

This C# program calculates and displays an upper triangular matrix based on user input. Problem Statement: The program takes the...
This C# program serves as a demonstration of bitwise operators, which are fundamental operators used for manipulating individual bits in...
This C# program is designed to interchange or swap the columns of a matrix. A matrix is a two-dimensional array...