Telerik blogs
How ToT Light_870x220

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. When this code runs, an InvalidCastException will be thrown 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:

  1. source array (sourceArray)
  2. starting index of source array (sourceIndex)
  3. destination array (destinationArray)
  4. starting index of destination array (destinationIndex)
  5. number of elements to copy (length)

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! 🚀


Peter Mbanugo
About the Author

Peter Mbanugo

Peter is a software consultant, technical trainer and OSS contributor/maintainer with excellent interpersonal and motivational abilities to develop collaborative relationships among high-functioning teams. He focuses on cloud-native architectures, serverless, continuous deployment/delivery, and developer experience. You can follow him on Twitter.

Comments

Comments are disabled in preview mode.