iTayb
iTayb

Reputation: 12743

What's the point using String.ToCharArray if a string is a char array itself?

string s = "string";
Console.WriteLine(s[1]); // returns t

char[] chars = s.ToCharArray();
Console.WriteLine(chars[1]); // also returns t

so what is the point in this method?

Upvotes: 6

Views: 710

Answers (3)

AakashM
AakashM

Reputation: 63338

Just because you can write s[1] doesn't mean that a string is a char array, it meerely means string has an indexer that returns a char. The fact that indexers are accessed with the same syntax as array member access is a C# language feature.

Upvotes: 5

to StackOverflow
to StackOverflow

Reputation: 124696

System.String isn't a character array. If you need a character array (e.g. to pass as an argument to a method that's expecting one), you will need to do this conversion.

Upvotes: 3

John Saunders
John Saunders

Reputation: 161773

A string is not a char array. You are confusing the fact that it has an indexer returning char with it being a char array.

Upvotes: 11

Related Questions