How to use C# string CopyTo

The CopyTo method of the string object assumes a crucial role in facilitating the precise copying of a specified number of characters from a given position within the string to a designated position within an array of characters. This method offers developers a powerful mechanism for extracting and transferring a targeted segment of characters to a desired location within an array.

When the CopyTo method is invoked, it initiates a meticulous process of extracting a designated number of characters from a specific position within the source string. These extracted characters are then accurately copied to the designated position within the target character array. This procedure ensures a precise and controlled transfer of characters, preserving the integrity and order of the extracted segment.

void string.CopyTo(int sourceIndex,char[] destination, int destinationindex,int count)
  1. int sourceIndex : The starting position of the source String.
  2. char[] destination : The character Array.
  3. int destinationindex : Array element in the destination.
  4. int count : The number of characters to destination.

CopyTo method in C#

By using the CopyTo method in C#, programmers gain the ability to extract and transfer a segment of characters to an array for further processing or manipulation. This functionality is particularly useful when specific subsets of characters need to be isolated and operated upon separately, or when the extracted characters need to be utilized in a different context altogether.

Full Source C#
using System; using System.Windows.Forms; namespace WindowsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { string str1 = "CopyTo() sample"; char[] chrs = new char[6]; str1.CopyTo(0, chrs, 0, 6); MessageBox.Show(chrs[0].ToString() + chrs[1].ToString() + chrs[2].ToString()+ chrs[3].ToString() + chrs[4].ToString() + chrs[5].ToString()); } } }

When you run this C# Source code you will get CopyTo in MessageBox

The CopyTo method empowers developers with a high level of control and precision when working with string data, allowing for efficient extraction and transfer of character segments to arrays. This capability facilitates advanced data processing and manipulation techniques, enhancing the flexibility and versatility of the C# programming language.


The C# string CopyTo method offers developers a reliable and precise means of copying a specified number of characters from a designated position within a string to a specific position within an array of characters. This capability enhances the flexibility and efficiency of data handling, providing programmers with a powerful tool to achieve their desired objectives when working with string data in C# applications.