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!

3
  • Take a look at this answer regarding array assignment/reference in C# Commented Jun 2, 2017 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. Commented Jun 2, 2017 at 12:39
  • Replace char[] reverseArray = new char[example.Length]; reverseArray = myArray; Array.Reverse(reverseArray); with var reverseArray = myArray.Reverse().ToArray(); Commented Jun 2, 2017 at 13:12

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.