Enumerating Through a String

I discovered something cool about strings the other day, and I must admit it is incredibly obviously and I do feel a rather stupid for not knowing this. I’ve never seen any code using this technique to enumerate through the characters in a string, maybe you have?

So normally developers would usually do something like this to enumerate through the characters in a string:


char[] charArray = "Hello World".ToCharArray();
foreach (char ch in charArray)
{
    // Do something (with ch)
}

Or maybe:


string value = "Hello World";
for (int index = 0; index < value.Length; index++)
{
    char ch = value[index];
    // Do something (with ch)
}

Or some other technique.

So I wanted to see if string implemented IFormattable, don’t ask why, it was a random thought going through my head and I discovered string implements a number of interesting interfaces, namely:

  • IComparable
  • ICloneable
  • IConvertible
  • IComparable
  • IEnumerable
  • IEnumerable
  • IEquatable

The most interesting being IEnumerable because it allows you to do the following:


foreach (char ch in "Hello World")
{
    // Do something (with ch)
}

And you can do LINQ queries directly against the characters in a string:


var ordinalValues = from ch in "Hello World"
                    select (int)ch;

Which I think is pretty cool :)