CHAPTER 3 CORE C# PROGRAMMING CONSTRUCTS, PART I
firstName
firstName
firstName
firstName
firstName
has 6 characters.
in uppercase: FREDDY
in lowercase: freddy
contains the letter y?: True
after replace: Fred
While this output might not seem too surprising, the output seen via calling the Replace() method is
a bit misleading. In reality, the firstName variable has not changed at all; rather, we receive back a new
string in a modified format. We will revisit the immutable nature of strings in just a few moments.
String Concatenation
string variables can be connected together to build larger strings via the C# + operator. As you might
know, this technique is formally termed string concatenation. Consider the following new helper
function:
static void StringConcatenation()
{
Console.WriteLine("=> String concatenation:");
string s1 = "Programming the ";
string s2 = "PsychoDrill (PTP)";
string s3 = s1 + s2;
Console.WriteLine(s3);
Console.WriteLine();
}
You might be interested to know that the C# + symbol is processed by the compiler to emit a call to
the static String.Concat() method. Given this, it is possible to perform string concatenation by calling
String.Concat() directly (although you really have not gained anything by doing so—in fact, you have
incurred additional keystrokes!).
static void StringConcatenation()
{
Console.WriteLine("=> String concatenation:");
string s1 = "Programming the ";
string s2 = "PsychoDrill (PTP)";
string s3 = String.Concat(s1, s2);
Console.WriteLine(s3);
Console.WriteLine();
}
Escape Characters
As in other C-based languages, C# string literals may contain various escape characters, which qualify
how the character data should be printed to the output stream. Each escape character begins with a
backslash, followed by a specific token. In case you are a bit rusty on the meanings behind these escape
characters, Table 3-6 lists the more common options.
97