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