Home > Mobile >  Updating array element by reassigning it to different variable?
Updating array element by reassigning it to different variable?

Time:11-27

First of all, sorry if this was asked before, but I simply could not find anything related to it.

string anElement = "World";
string[] col = new string[2] { "Hello", anElement };
anElement = "Jupiter";
Array.ForEach(col, Console.WriteLine);

// Output:
// Hello
// World

As can be seen, reassigning a different value to the anElement reference doesn't update the value.

Same also applies in this scenario:

string[] col = new string[2] { "Hello", "World" };
string elementToUpdate = col[1];
elementToUpdate = "Jupiter";
Array.ForEach(col, Console.WriteLine);

If all the elements are stored as references, why changing col[1]="Jupiter" works while the above does not?

CodePudding user response:

Try this code instead

string anElement = "World";
string[] col = new string[2] { "Hello", anElement };
col[1] = "Jupiter";
Array.ForEach(col, Console.WriteLine);

The problem is you were assigning the value to the anElement, and not getting the item within the array where you needed to make the change

CodePudding user response:

Because local variable string anElement assigned is not used in any execution path. Try this code instead

        string anElement = "World";
        anElement = "Jupiter";
        string[] col = new string[2] { "Hello", anElement };
        Array.ForEach(col, Console.WriteLine);

        // Output:
        // Hello
        // Jupiter
  • Related