HomeCSharpC# Error CS0202 – foreach requires that the return type ‘type’ of ‘type.GetEnumerator()’

C# Error CS0202 – foreach requires that the return type ‘type’ of ‘type.GetEnumerator()’

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

C# Error CS0202 - foreach requires that the return type 'type' of 'type.GetEnumerator()'

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

}

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