1

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];
}
Jianjie
  • 107
  • 5
  • 2
    `ref var q = ref method(ref s);` • See [Ref locals](https://learn.microsoft.com/dotnet/csharp/language-reference/keywords/ref#ref-locals) and [Ref Returns, Ref Locals, and how to use them](https://www.danielcrabtree.com/blog/128/c-sharp-7-ref-returns-ref-locals-and-how-to-use-them) –  Aug 15 '21 at 08:53
  • Does this answer your question? [Why doesn't C# support the return of references?](https://stackoverflow.com/questions/6339602/why-doesnt-c-sharp-support-the-return-of-references) and [C# 7 ref return for reference types](https://stackoverflow.com/questions/48310345/c-sharp-7-ref-return-for-reference-types) –  Aug 15 '21 at 08:56
  • See this https://www.tutorialspoint.com/cplusplus/returning_values_by_reference.htm – I_Al-thamary Aug 15 '21 at 09:02

1 Answers1

1

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 a ref 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 by GetContactInformation. Any future assignments to p will not change the value of the variable returned by GetContactInformation. The variable p 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);
Sweeper
  • 213,210
  • 22
  • 193
  • 313