System.String.CopyTo Method

Copies a specified number of characters from a specified position in this instance to a specified position in an array of Unicode characters.


public void CopyTo (int sourceIndex, char[] destination, int destinationIndex, int count)


The index of the first character in this instance to copy.
An array of Unicode characters to which characters in this instance are copied.
The index in destination at which the copy operation begins.
The number of characters in this instance to copy to destination.


ArgumentNullException destination is a null reference.

sourceIndex, destinationIndex, or count is negative


count is greater than the length of the substring from startIndex to the end of the current instance


count is greater than the length of the subarray from destinationIndex to the end of destination


This method copies count characters from the sourceIndex position of this instance to the destinationIndex position of destination character array. This method does not resize the destination character array; it must have a sufficient number of elements to accommodate the copied characters or the method throws an ArgumentOutOfRangeException.

sourceIndex and destinationIndex are zero-based.


The following example demonstrates copying characters from a string to a Unicode character array.

C# Example

using System;
public class StringCopyToExample {
 public static void Main() {
 string str = "this is the new string";
 Char[] cAry = {'t','h','e',' ','o','l','d'};
 Console.WriteLine( "The initial string is '{0}'", str );
 Console.Write( "The initial character array is: '" );
 foreach( Char c in cAry)
 Console.Write( c );
 Console.WriteLine( "'" );
 str.CopyTo( 12, cAry, 4, 3 );
 Console.Write( "The character array after CopyTo is: '" );
 foreach( Char c in cAry)
 Console.Write( c );

The output is

The initial string is 'this is the new string'
The initial character array is: 'the old'
The character array after CopyTo is: 'the new'


Namespace: System
Assembly: mscorlib (in mscorlib.dll)
Assembly Versions: 1.0.5000.0,,