

Copying and Cloning Arrays in C#
source link: https://www.tuicool.com/articles/hit/FZnIrar
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Learn how to copy elements from one array to another using the provided functions in System.Array class.
An array in C# is a collection of data items, all of the same type and accessed using a numeral index. The Array
class provides methods for creating, manipulating, searching, and sorting arrays in .NET. There will be situations where you want to work with a new array but copy items from an existing array to it, or copy items from one array into another array. I’ll show you how to do this using some available methods in the Array class.
Array.CopyTo
Array.CopyTo
copies all the elements of the current array to the specified destination array. This method should be called from the source array and it takes two parameters. The first being the array you want to copy to, and the second parameter tells it what index of the destination array it should start copying into. Let’s take a look at an example.
var source = new[] { "Ally", "Bishop", "Billy" }; var target = new string[4]; source.CopyTo(target, 1); foreach (var item in target) { Console.WriteLine(item); } // output: // Ally // Bishop // Billy
The code above copies all items in the source array to the target array. It copies elements from the source to the target array object starting at index 1
; therefore, index 0
of the target array is null.
Array.ConstrainedCopy
Array.ConstrainedCopy
is similar to Array.CopyTo
. The difference is that Array.ConstrainedCopy
guarantees that all changes are undone if the copy operation does not succeed completely because of some exception. Here’s an example of how Array.CopyTo
behaves when it encounters an exception.
var source = new object[] { "Ally", "Bishop", 1 }; var target = new string[3]; try { source.CopyTo(target, 0); } catch (InvalidCastException) { foreach (var element in target) { Console.WriteLine(element); } } Console.Read(); // output: // Ally // Bishop
Above, we have a source array that has elements of string and object type. We copy the content from the source array into a target array, which is a string type. When this code runs, it’ll encounter an InvalidCastException
when it tries to copy the last element, which does not match the type of the target array. The copy operation fails at that point, but the target array already has some of the element from the source array from what we see printed in the console. Let’s try a similar example with ConstrainedCopy
:
var source = new object[] { "Ally", "Bishop", 1 }; var target = new string[3]; try { Array.ConstrainedCopy(source, 0, target, 0, 3); } catch (ArrayTypeMismatchException) { Console.WriteLine(target[0]); Console.WriteLine(target[1]); } Console.Read();
Array.ConstrainedCopy
takes five (5) parameters: the source array and its starting index, the target array and its starting index, and an integer representing the number of elements to copy. When the code above runs, it encounters an exception, and, when you check the content of the target array, you’ll notice it has nothing in it, unlike Array.CopyTo
.
Array.ConvertAll
Array.ConvertAll
is used to convert an array of one type to an array of a different type. The method takes the source array as the first parameter, and then a second parameter of Converter<TInput,TOutput>
delegate. This delegate represents a conversion function to convert from one type to another.
Assume the following class:
class Person { public Person(string name) { Name = name; } public string Name { get; private set; } }
Here is an example of Array.ConvertAll
being used with this type:
var source = new[] { "Ally", "Bishop", "Billy" }; var target = Array.ConvertAll(source, x => new Person(x)); foreach (var item in target) { Console.WriteLine(item.Name); } Console.Read(); // output: // Ally // Bishop // Billy
Here we are taking an array of string and making a new array of Person
out of it. This comes in handy when we want to make a new array that copies data from another array.
Array.Clone Method
Array.Clone
does a shallow copy of all the elements in the source array and returns an object containing those elements. Here’s an example of how you can use this method:
static void Main(string[] args) { var source = new[] { "Ally", "Bishop", "Billy" }; var target = (string[])source.Clone(); foreach (var element in target) { Console.WriteLine(element); } Console.Read(); } // output: // Ally // Bishop // Billy
Array.Clone
returns an object that we have to cast to an array of strings. This differs from Array.CopyTo
because it doesn’t require a target/destination array to be available when calling the function, whereas Array.CopyTo
requires a destination array and an index.
Conclusion
The Array
class in C# is very useful when working with a collection of data. It provides methods for creating, manipulating, searching, and sorting arrays. In this post, I showed you how to copy data from one array object to another. You saw the various methods available from the Array class. They are Clone
, CopyTo
, ConstrainedCopy
, and ConvertAll
methods. The various examples showed you how to use these methods, and I believe this should leave you with additional knowledge on working with arrays in C#.
Feel free to leave a comment if you have any questions. Happy coding! :rocket:
Recommend
-
19
-
38
Guest Author : Sander Stad ( @sqlstad ) PSDatabaseClone is a PowerShell module that has the ability to create images of databases ("clones") and distribute those cl...
-
5
Cloning a reference and method call syntax in Rust By Michael Snoyman, December 28, 2020 Share this ...
-
12
Cloning and changing readonly properties in PHP 8.1 By continuing your visit to this site, you accept the use of cookies. Read more. S...
-
5
Voice cloning of growing interest to actors and cybercriminalsBy Kitti PalmaiBusiness reporterPublished20 hours agoimage copyrightTim Hellerimage captionTim Heller is a...
-
5
Transcript Palomino: Welcome to my QCon presentation on production infrastructure cloning++, an emphasis on reliability and repeatability. I am your host and emcee J.D. Palomino. Introduction Firstl...
-
10
« back — written by Brent on July 06, 2021 PHP 8.1: cloning and changing readonly properties ...
-
2
@bumblebeeSonia JessicaTech Blogger and Content Marketer
-
5
Android and Windows 11 are copying Apple’s ecosystem again
-
7
Copying Designs Doesn’t Work, And Here’s WhyStriking the right balance between inspiration and innovation might be hard. Let’s explore how to effectively get inspiration from others...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK