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