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

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