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.