Why would ref be used for array parameters in C#?

2019-02-17 05:11发布

问题:

I read the page Passing Arrays Using ref and out (C# Programming Guide) and was wondering why we would need to define an array parameter as a ref parameter when it is already a reference type. Won't changes in the callee function be reflected in the caller function?

回答1:

Won't changes in the callee function be reflected in the caller function?

Changes to the contents of the array would be reflected in the caller method - but changes to the parameter itself wouldn't be. So for example:

public void Foo(int[] x)
{
    // The effect of this line is visible to the caller
    x[0] = 10;

    // This line is pointless
    x = new int[] { 20 };
}
...
int[] original = new int[10];
Foo(original);
Console.WriteLine(original[0]); // Prints 10

Now if we changed Foo to have a signature of:

public void Foo(ref int[] x)

and changed the calling code to:

Foo(ref original);

then it would print 20.

It's very important to understand the difference between a variable and the object that its value refers to - and likewise between modifying an object and modifying a variable.

See my article on parameter passing in C# for more information.



回答2:

If you only plan to change the contents of the array, then you're correct. However, if you plan on changing the array itself, then you must pass by reference.

For example:

void foo(int[] array)
{
  array[0] = 5;
}

void bar(int[] array)
{
  array = new int[5];
  array[0] = 6;
}

void barWithRef(ref int[] array)
{
  array = new int[6];
  array[0] = 6;
}


void Main()
{
  int[] array = int[5];
  array[0] = 1;

  // First, lets call the foo() function.
  // This does exactly as you would expect... it will
  // change the first element to 5.
  foo(array);

  Console.WriteLine(array[0]); // yields 5

  // Now lets call the bar() function.
  // This will change the array in bar(), but not here.
  bar(array);

  Console.WriteLine(array[0]); // yields 1.  The array we have here was never changed.

  // Finally, lets use the ref keyword.
  barWithRef(ref array);

  Console.WriteLine(array[0]); // yields 5.  And the array's length is now 6.
}


标签: c# out ref