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

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