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

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

Leave a Reply

You May Also Like

This C# program calculates and displays an upper triangular matrix based on user input. Problem Statement: The program takes the...
This C# program serves as a demonstration of bitwise operators, which are fundamental operators used for manipulating individual bits in...
This C# program is designed to interchange or swap the columns of a matrix. A matrix is a two-dimensional array...