Search code examples
c#arraysarray-reverse

C# Array.Reverse reversing the original array passed by value to method


I have a char array in one method, someObject is an arbitrary object passed by reference to the GetChars method:

private void DoSomeStuff(ref Object someObject)
{
   char[] chars = GetChars(ref someObject); // {'a','b','c','d'}
   char[] ReversedChars = Reverse(chars); // {'d','d','b','a'}
   //chars and ReversedChars are in the same order, although "ref" is not used
}

private char[] Reverse(char[] someChars)
{
   Array.Reverse(someChars);
   return someChars;
}

Why is Array.Reverse in another method changing the original passed char array if not passing it by reference?


Solution

  • Arrays are objects, so: reference-types.

    It is passing a reference - by value. So: if you change what the reference points to (i.e. the array data), that change will still be visible to everyone who also has a reference to that same object.

    There is only one array here; there is literally no other data that could be changed.

    Passing a reference by-reference is only meaningful if you will reassign the reference to a different object.