C# Error CS8154 – The body of ‘{0}’ cannot be an iterator block because ‘{0}’ returns by reference

C# Error

CS8154 – The body of ‘{0}’ cannot be an iterator block because ‘{0}’ returns by reference

Reason for the Error & Solution

The body cannot be an iterator block because it returns by reference

Example

The following sample generates CS8154:

// CS8154.cs (12,17)

class TestClass
{
    int x = 0;
    ref int TestFunction()
    {
        if (true)
        {
            yield return x;
        }

        ref int localFunction()
        {
            if (true)
            {
                yield return x;
            }
        }

        yield return localFunction();
    }
}

To correct this error

Iterator methods cannot return by reference, refactoring to return by value corrects this error:

class TestClass
{
    int x = 0;
    IEnumerable<int> TestFunction()
    {
        if (true)
        {
            yield return x;
        }

        IEnumerable<int> localFunction()
        {
            if (true)
            {
                yield return x;
            }
        }

        foreach (var item in localFunction())
            yield return item;
    }
}

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