Copy a 2-dimensional array in C#
This post will discuss how to a copy 2-dimensional array in C#.
A simple and straightforward solution to create a shallow copy of an array is using the Array.Clone() method. Consider the following example, which clones a 2D array of integer type. Note that the clone is of the same type as the source array.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
using System; public class Example { public static void Main() { int[,] arr = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; // clone the 2D array int[,] copy = arr.Clone() as int[,]; // print the 2D array for (int i = 0; i < copy.GetLength(0); i++) { for (int j = 0; j < copy.GetLength(1); j++) { Console.Write("{0} ", copy[i, j]); } Console.WriteLine(); } } } |
Output:
1 2 3
4 5 6
7 8 9
That’s all about copying a 2-dimensional array in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)