tags:

views:

422

answers:

3

Can any one explain why the output of this code is only 'hello' and what this code means?

( 0, characterArray, 0, characterArray.Length );

The output is showing:

The character array is: hello

The code follows:

string string1 = "hello there";
char[] characterArray = new char[ 5 ];

string1.CopyTo( 0, characterArray, 0, characterArray.Length );
Console.Write( "\nThe character array is: " );

for ( int i = 0; i < characterArray.Length; i++ )
    Console.Write( characterArray[ i ] );

Thanx in advance.

+5  A: 

It's because your array is only set for 5 characters. Expand it to 11 and it will work.

Here is what the Copyto is:

public void CopyTo(
    int sourceIndex,
    char[] destination,
    int destinationIndex,
    int count
)
Parameters
sourceIndex
Type: System..::.Int32
A character position in this instance. 

destination
Type: array[]()[]
An array of Unicode characters. 

destinationIndex
Type: System..::.Int32
An array element in destination. 

count
Type: System..::.Int32
The number of characters in this instance to copy to destination. 

Taken from: http://msdn.microsoft.com/en-us/library/system.string.copyto.aspx

AaronS
What does this mean sweety ( 0, characterArray, 0, characterArray.Length );
You have got to be kidding me! Three upvotes for that!? :-)
Lette
thanx Aaron Love ya
+2  A: 

It's only showing 'hello' because your character array is only 5 chars long. As for the parameters to CopyTo, read http://msdn.microsoft.com/en-us/library/system.string.copyto.aspx

Cody Brocious
A: 

That's because your character array size is only 5. if you want the whole string as an array, you can you string.ToCharArray instead

sthay