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?
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.
See more on this question at Stackoverflow