HomeCSharpC# Error CS8169 – Cannot return a member of local ‘{0}’ by reference because it is not a ref local

C# Error CS8169 – Cannot return a member of local ‘{0}’ by reference because it is not a ref local

C# Error

CS8169 – Cannot return a member of local ‘{0}’ by reference because it is not a ref local

Reason for the Error & Solution

Cannot return a member of local by reference because it is not a ref local

Example

The following sample generates CS8169:

// CS8169.cs (17,15)

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

    ref char Test1(char arg1, ref S1 arg2)
    {
        S1 l = default(S1);
        // valid
        ref char r = ref l.x;

        // invalid
        return ref l.x;
    }
}

Using a ref to S1.x within the Test1 method is valid because use of the reference does not leave the scope of the value type l. Upon returning from Test, l would become invalid along with any references to its properties.

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