C# Error CS1640 – foreach statement cannot operate on variables of type ‘{0}’ because it implements multiple instantiations of ‘{1}’; try casting to a specific interface instantiation

C# Error

CS1640 – foreach statement cannot operate on variables of type ‘{0}’ because it implements multiple instantiations of ‘{1}’; try casting to a specific interface instantiation

Reason for the Error & Solution

foreach statement cannot operate on variables of type ‘type’ because it implements multiple instantiations of ‘interface’, try casting to a specific interface instantiation

The type inherits from two or more instances of IEnumerator<T>, which means there is not a unique enumeration of the type that foreach could use. Specify the type of IEnumerator<T> or use another looping construct.

Example

The following sample generates CS1640:

// CS1640.cs  
  
using System;  
using System.Collections;  
using System.Collections.Generic;  
  
public class C : IEnumerable, IEnumerable<int>, IEnumerable<string>  
{  
    IEnumerator<int> IEnumerable<int>.GetEnumerator()  
    {  
        yield break;  
    }  
  
    IEnumerator<string> IEnumerable<string>.GetEnumerator()  
    {  
        yield break;  
    }  
  
    IEnumerator IEnumerable.GetEnumerator()  
    {  
        return (IEnumerator)((IEnumerable<string>)this).GetEnumerator();  
    }  
}  
  
public class Test  
{  
    public static int Main()  
    {  
        foreach (int i in new C()){}    // CS1640  
  
        // Try specifying the type of IEnumerable<T>  
        // foreach (int i in (IEnumerable<int>)new C()){}  
        return 1;  
    }  
}  

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...