0

I'm struggling to wrap my head around the issue I'm having when I'm running the program below:

using System;

namespace StringReversal
{
   class MainClass
   {
    public static void Main(string[] args)
    {
        string example = "word";
        char[] myArray = new char[example.Length];          
        myArray = example.ToCharArray(0, example.Length);

        char[] reverseArray = new char[example.Length];
        reverseArray = myArray;

        Array.Reverse(reverseArray);

        Console.WriteLine(myArray);
        Console.WriteLine(reverseArray);

      }
   }
 }

The output is as follows:

drow

drow

My best guess for the cause is that I'm using object references to assign myArray's value to reverseArrays, and then running the Array.Reverse() method on reverseArray.

While I'm sure this question has been discussed, I was wondering if I could get an explanation as to how this works in this manner. I assign values to variables all the time without an issue, like below:

 int x = 10;
 int y = 5;
 x = y;
 // x would then equal 5, correct?

Thanks for your insight!

Steve Boniface
  • 571
  • 1
  • 11
  • 23
  • Take a look at this [answer](https://stackoverflow.com/a/29398919/6224482) regarding array assignment/reference in C# – Sandman Jun 02 '17 at 12:39
  • `reverseArray = myArray;` here you have reference assignement, so both reverseArray and myArray are pointing to the same memory location (of myArray), so they present exactly the same values from that memory location. – pitersmx Jun 02 '17 at 12:39
  • Replace `char[] reverseArray = new char[example.Length]; reverseArray = myArray; Array.Reverse(reverseArray);` with `var reverseArray = myArray.Reverse().ToArray();` – mjwills Jun 02 '17 at 13:12

1 Answers1

2

You are assigning a reference to an array here in your code instead of making a copy:

reverseArray = myArray;

So as result you basically have 2 references to the same object. You have to copy myArray to reverseArray by calling Array.Copy, for instance

Anton Sorokin
  • 401
  • 1
  • 7
  • 10