C# Error CS8157 – Cannot return ‘{0}’ by reference because it was initialized to a value that cannot be returned by reference

C# Error

CS8157 – Cannot return ‘{0}’ by reference because it was initialized to a value that cannot be returned by reference

Reason for the Error & Solution

Cannot return by reference because it was initialized to a value that cannot be returned by reference

Example

The following sample generates CS8157:

// CS8157.cs (8,21)

class C
{
    ref int M()
    {
        int x = 0;
        ref int rx = ref x;
        return ref (rx = ref (new int[1])[0]);
    }
}

To correct this error

To return a value that cannot be returned by reference, refactoring to return by value corrects this error:

class C
{
    int M()
    {
        int x = 0;
        ref int rx = ref x;
        return rx = ref (new int[1])[0];
    }
}

Leave A Reply

Your email address will not be published. Required fields are marked *

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