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

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...