kataba
kataba

Reputation: 170

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?

Upvotes: 2

Views: 1066

Answers (3)

Lionize
Lionize

Reputation: 51

As an array is a referenced type, you would need to make a copy of your array if you do not want to affect your original values.

To do so, update your Reverse method to this:

private char[] Reverse(char[] someChars)
    {
        char[] cloneArray = someChars.Clone() as char[];
        Array.Reverse(cloneArray);
        return cloneArray;
    }

Upvotes: 1

Steve Todd
Steve Todd

Reputation: 1270

Arrays are reference types (they are a kind of object according to .NET). When you call your routine you are returning the same reference, and are only changing the order of the elements within it.

Copy the array before you reverse the results if you want it not to effect the original.

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1062620

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.

Upvotes: 3

Related Questions