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 q
is not a ref local. It is just a regular variable. You are also not saying ref
before the method call, so this is just a regular by-value assignment. Because of these reasons, q
is not an alias of a[0]
.
The documentation gives a similar example:
Assume the
GetContactInformation
method is declared as aref return
:public ref Person GetContactInformation(string fname, string lname)
A by-value assignment reads the value of a variable and assigns it to a new variable:
Person p = contacts.GetContactInformation("Brandie", "Best");
The preceding assignment declares
p
as a local variable. Its initial value is copied from reading the value returned byGetContactInformation
. Any future assignments top
will not change the value of the variable returned byGetContactInformation
. The variablep
is no longer an alias to the variable returned.
To fix this, you would add ref
before var
to make q
a ref local, and also add ref
before the call to make it a by-ref assignment:
ref var q = ref method(ref s);