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.

Syntax

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

Parameters

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

Exceptions

TypeReason
ArgumentNullException destination is a null reference.
ArgumentOutOfRangeException

sourceIndex, destinationIndex, or count is negative

-or-

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

-or-

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

Remarks

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.

Example

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 );
 Console.WriteLine("'");
 }
}
   

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'

Requirements

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