C# Error CS8374 – Cannot ref-assign ‘{1}’ to ‘{0}’ because ‘{1}’ has a narrower escape scope than ‘{0}’.

C# Error

CS8374 – Cannot ref-assign ‘{1}’ to ‘{0}’ because ‘{1}’ has a narrower escape scope than ‘{0}’.

Reason for the Error & Solution

Cannot ref-assign to because has a narrower escape scope than.

Example

The following sample generates CS8374 because the reference contained in r1 is externally visible but the scope of rx‘s value (its lifetime) is local:

// CS8374.cs (6,9)

class C
{
    void M(ref int r1)
    {
        int x = 0;
        ref int rx = ref x;
        for (int i = 0; i < (r1 = ref rx); i++)
        {
        }
    }
}