0

How do you set the values of an array to another without affecting the original array?

float[] baseArray = new float[] {1, 2, 3, 4};
float[] newArray = baseArray;
newArray[0] = 5;
print(newArray[0]);
print(baseArray[0]);

It outputs 5 twice but I want the base array to remain unaffected and output 1. How would I assign the newArray by value instead of by reference?

  • 3
    You need to create another array, there's no other way. Shortest possible is probably Linq's `ToArray` -> `var newArray = baseArray.ToArray();` – Camilo Terevinto Aug 11 '21 at 15:24
  • Be aware that if you end up using reference types (i.e. class instances), you'll also need to manually copy the class data too (deep copy) otherwise you'll end up with two different arrays that hold references to the same class objects (shallow copy). You're safe at the moment though, because `float` is a value type :) – ProgrammingLlama Aug 11 '21 at 15:27
  • Array objects has a CopyTo function. You can use it to copy all data to another array. But as @CamiloTerevinto said first you have to create another empty array. – Ashish Sinha Aug 11 '21 at 15:27

0 Answers0