So I've got a simple string array. Passed it to a function that reverses its input and then displayed the content of the array. I was expecting the contents of the array to reverse since arrays are passed by reference, but the string array did not change.
string[] words = { "Metal", "Gear", "is", "Awesome!" };
mutateArray(ref words);
foreach (string word in words)
Console.Write(word + " ");
This is my mutateArray
function:
public static void mutateArray(ref string[] arr)
{
arr = arr.Reverse().ToArray();
}
I know that the mutateArray
method changes to the array will persist once I state that the parameter must be passed in with the keyword ref
.
- Aren't all arrays passed in by reference by default?
- Why do the changes persist when the keyword ref is involved?
- What's the difference between passing a reference type (
classes
,interfaces
,array
,delegates
) by value vs passing them by reference (with the keywordref
)?