18

Possible Duplicate:
C#: Any faster way of copying arrays?

I have an integer array

int[] a;

I want to assign a copy of it(not reference) to

int[] b;

what is the easier way to do it?

Community
  • 1
  • 1
william007
  • 17,375
  • 25
  • 118
  • 194

3 Answers3

31

You can use the native Clone method, try something like this:

int[] b = (int[])a.Clone();

Other options are, using linq:

using System.Linq;

// code ...
int[] b = a.ToArray();

And copying the array

int[] b = new int[a.Length];
a.CopyTo(b, 0);
Felipe Oriani
  • 37,948
  • 19
  • 131
  • 194
5

I think simplest way would be

int[] b = a.ToArray();
I4V
  • 34,891
  • 6
  • 67
  • 79
  • This requires `using System.Linq;` before it works. – Gerard Aug 31 '17 at 11:28
  • SUPER late but I am pretty sure Linqs ToArray checks the underlying type and, if it is an array, just returns immediately. – Marie Jul 11 '18 at 18:20
  • 2
    @Marie It most certainly cannot return immediately, as LINQ methods like `ToList` and `ToArray` return a new collection. That is very important when modifying the resulting collection: the original collection is not modified. LINQ does optimize the `ToArray` implementation for types that implement `ICollection`, as their `Count` property lets it create an array of the correct size immediately. – Timo Aug 29 '19 at 15:25
3

You can use Array.CopyTo method.

int[] a = new[] { 1, 2, 3 };
int[] b = new int[3];
a.CopyTo(b,0);
oleksii
  • 35,458
  • 16
  • 93
  • 163