C# Error CS8172 – Cannot initialize a by-reference variable with a value

C# Error

CS8172 – Cannot initialize a by-reference variable with a value

Reason for the Error & Solution

Cannot initialize a by-reference variable with a value

Example

The following sample generates CS8172:

// CS8172.cs (10,17)

class C
{
    void M()
    {
        ref readonly int L() => ref (new int[1])[0];

        ref readonly int x = ref L();
        ref int y = x;
    }
}

To correct this error

Assigning a reference to a variable to a by-reference variable corrects this error:

class C
{
    void M()
    {
        ref readonly int L() => ref (new int[1])[0];

        ref readonly int x = ref L();
        ref int y = ref x;
    }
}