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

C# Error

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

Reason for the Error & Solution

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

Example

The following sample generates CS8158:

// CS8158.cs (11,14)

public class Test
{
    public struct S1
    {
        public char x;
    }

    ref char Test1(char arg1, S1 arg2)
    {
        ref S1 r = ref arg2;
        return ref r.x;
    }
}

To correct this error

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

    char Test1(char arg1, S1 arg2)
    {
        ref S1 r = ref arg2;
        return r.x;
    }

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