It will come as no surprise that the .NET Framework provides
us with two types that correspond with strings and characters: String
and Char
. In fact, as we’ve
seen before, these are such important types that C# even provides us with
keywords that correspond to the underlying types: string
and char
.
String
needs to provide us with
that “ordered sequence of characters” behavior. It does so by implementing
IEnumerable<char>
, as Example 10-1 illustrates.
Example 10-1. Iterating through the characters in a string
string myString = "I've gone all vertical."; foreach (char theCharacter in myString) { Console.WriteLine(theCharacter); }
If you create a console application for this code, you’ll see output like this when it runs:
I ' v e g o n e a l l v e r t i c a l .
What exactly does that code do? First, it initializes a variable
called myString
which we will use to
hold the reference to our string object (because String
is a reference type).
We then enumerate the string, yielding every Char
in turn, and we output each Char
to the console on its own separate line.
Char
is a value type, so we’re actually
getting a copy of the character from the string
itself.
The string object is created using a literal string—a sequence of characters enclosed in double quotes:
"I've gone all vertical."
We’re already quite familiar with initializing a string with a literal—we probably do it without a second thought; but let’s have a look at these literals in a little more detail.