-2

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
  • 193
  • 2
  • 11

2 Answers2

0

Clone should work:

var newWords=(string[])words.Clone();
derHugo
  • 68,790
  • 9
  • 58
  • 97
hfpt
  • 124
  • 5
0

You could try wrapping your cloning logic in a method.

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

o_in25
  • 128
  • 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