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

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