C# Compiler Error
CS0202 – foreach requires that the return type ‘type’ of ‘type.GetEnumerator()’ must have a suitable public MoveNext method and public Current property
Reason for the Error
You will receive this error when you return either a pointer or an array from a GetEnumerator function in your C# code.
For example, try to compile the below code snippet.
using System; using System.Collections; namespace DeveloperPubNamespace { public class Days { string[] tage = { "mon", "tue", "wed", "thu", "fri" }; public IEnumerator[] GetEnumerator() { for (int i = 0; i < tage.Length; i++) yield return tage[i]; } } class Program { static void Main(string[] args) { Days daylist = new Days(); foreach (string s in daylist) { Console.WriteLine(s); } } } }
This program will result with the error code CS0202 because the GetEnumerator returns IEnumerator[] which is an array.
Error CS0202 foreach requires that the return type ‘IEnumerator[]’ of ‘Days.GetEnumerator()’ must have a suitable public ‘MoveNext’ method and public ‘Current’ property ConsoleApp3 C:\Users\SenthilBalu\source\repos\ConsoleApp3\ConsoleApp3\Program.cs 20 Active
Solution
To fix the error code CS0202, you will need to ensure that the function GetEnumerator always returns an instanxe of a class of type Enumerator. The above code can fixed by renaming the return type to IEnumerator from IEnumerator[].
using System; using System.Collections; namespace DeveloperPubNamespace { public class Days { string[] tage = { "mon", "tue", "wed", "thu", "fri" }; public IEnumerator GetEnumerator() { for (int i = 0; i < tage.Length; i++) yield return tage[i]; } } class Program { static void Main(string[] args) { Days daylist = new Days(); foreach (string s in daylist) { Console.WriteLine(s); } } } }