I plan to return a reference of a value in an array (and manipulate it), however, when I pass the array in method(), the result is not what I want.
And I also curious about the fact that I can't use DEBUG monitor to query the address of &a in method() stack.
Any one could help me with the correct use of return ref?
static void Main(string[] args)
{
int?[] s = new int?[5] { 1, 2, 3, 4, 5 };
var q = method(ref s);
q = 999;
Console.WriteLine("s0 is " + s[0].ToString());
}
static ref int? method(ref int?[] a)
{
a[1] = 888;
return ref a[0];
}
This happens because
qis not a ref local. It is just a regular variable. You are also not sayingrefbefore the method call, so this is just a regular by-value assignment. Because of these reasons,qis not an alias ofa[0].The documentation gives a similar example:
To fix this, you would add
refbeforevarto makeqa ref local, and also addrefbefore the call to make it a by-ref assignment: