Compiler Error CS1640
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;
}
}
Collaborate with us on GitHub
The source for this content can be found on GitHub, where you can also create and review issues and pull requests. For more information, see our contributor guide.
Feedback
https://aka.ms/ContentUserFeedback.
Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see:Submit and view feedback for