-1

So let's say I have an array like this:

string[] words = new string[3];
words[0] = "welcome";
words[1] = "hello";
words[2] = "hey";

and I want to clone/copy it and will modify it:

string[] new_words = words;
new_words[1] = "hi!";

The problem is that it actually changes the words[1] = "hello"; to words[1] = "hi!"; as well which is not what I wanted to do. How can I copy/clone an array and modify it without affecting its source? Thank you so much!

Dranreb
  • 313
  • 3
  • 11

2 Answers2

0

Clone should work:

var newWords=(string[])words.Clone();
derHugo
  • 83,094
  • 9
  • 75
  • 115
hfpt
  • 124
  • 5
  • Thanks! But if I do that I cannot access it anymore? `newWords[0]...` it will say `Cannot apply indexing with [] to an expression of type 'object'` – Dranreb Aug 03 '21 at 19:38
  • After casting to `string[]` this isn't just an `object` anymore ... – derHugo Aug 03 '21 at 20:39
0

You could try wrapping your cloning logic in a method.

void Swap(string[] arr) => arr[0] = "Temp";

o_in25
  • 136
  • 1
  • 9
  • Thank you! But can you give me context to what that code does? (I'm not really familiar with it). – Dranreb Aug 03 '21 at 19:39