C# Error CS8176 – Iterators cannot have by-reference locals

C# Error

CS8176 – Iterators cannot have by-reference locals

Reason for the Error & Solution

Iterators cannot have by-reference locals

Iterator blocks use deferred execution, where the evaluation of an expression is delayed until its realized value is actually required. To manage that deferred execution state, iterator blocks use a state machine, capturing variable state in closures implemented in compiler-generated classes and properties. A local variable reference (on the stack) cannot be captured within the instance of a class in the heap, so the compiler issues an error.

Example

The following sample generates CS8176:

// CS8176.cs (7,26)

using System.Collections.Generic;
class C
{
    IEnumerable<int> M()
    {
        ref readonly int x = ref (new int[1])[0];
        int i = x;
        yield return i;
    }
}

To correct this error

Removing use of by-reference corrects this error:

class C
{
    IEnumerable<int> M()
    {
        int x = (new int[1])[0];
        int i = x;
        yield return i;
    }
}

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