2

Why on Earth would someone convert a string to a char[] before enumerating the characters in it? The regular pattern for initializing a System.Security.SecureString found all around the net follows:

SecureString secureString = new SecureString();
foreach (char c in "fizzbuzz".ToCharArray())
{
    secureString.AppendChar(c);
}

Calling ToCharArray() makes no sense for me. Could someone tell whether I am wrong here?

wigy
  • 2,174
  • 19
  • 32

2 Answers2

6

Since string implements IEnumerable<char>, it's not necessary in this context. The only time you need ToCharArray is when you actually need an array.

My guess is that most people who call ToCharArray don't know that string implements IEnumerable (even though as far as I know it always has).

Gabe
  • 84,912
  • 12
  • 139
  • 238
  • Thanks. Reading http://stackoverflow.com/questions/2420122/using-securestring and http://www.codekeep.net/snippets/8a3b075c-d74d-43ee-8937-1136289751de.aspx and http://social.technet.microsoft.com/Forums/en-CA/winserverpowershell/thread/4df7c4e6-bd5e-46b5-9a74-ac7c3d8c7314 I was really confused about why nobody left out this ToCharArray call. – wigy Apr 28 '11 at 00:05
  • A lot of it may be cargo cult programming. People see others do it and not ever investigate to understand why it's not necessary. – Gabe Apr 28 '11 at 00:07
1

Actually that is bad because it

  • enumerates on the string
  • creates an array with a copy of all chars
  • enumerates on that

A lot of unnecessary work...

That's because strings are immutable, and giving out a pointer to its internal array is not allowed, so ToCharArray() makes a copy instead of a cast.

That is:

you can enumerate a string as a char[] but:

you cannot:

var chars = (char[])"string";

If you would go enumerating and would want to break at some point, by using the toCharArray() would already have enumerated the whole string nad made a copy of all chars. If the string would be very big, that is quite expensive...

Marino Šimić
  • 7,318
  • 1
  • 31
  • 61