CHAPTER 3 CORE C# PROGRAMMING CONSTRUCTS, PART I
// The following string is printed verbatim,
// thus all escape characters are displayed.
Console.WriteLine(@"C:\MyApp\bin\Debug");
Also note that verbatim strings can be used to preserve white space for strings that flow over
multiple lines.
// White space is preserved with verbatim strings.
string myLongString = @"This is a very
very
very
long string";
Console.WriteLine(myLongString);
Using verbatim strings, you can also directly insert a double quote into a literal string by doubling
the " token.
Console.WriteLine(@"Cerebus said ""Darrr! Pret-ty sun-sets""");
Strings and Equality
As fully explained in Chapter 4, a reference type is an object allocated on the garbage-collected managed
heap. By default, when you perform a test for equality on reference types (via the C# == and !=
operators), you will be returned true if the references are pointing to the same object in memory.
However, even though the string data type is indeed a reference type, the equality operators have been
redefined to compare the values of string objects, not the object in memory to which they refer.
static void StringEquality()
{
Console.WriteLine("=> String equality:");
string s1 = "Hello!";
string s2 = "Yo!";
Console.WriteLine("s1 = {0}", s1);
Console.WriteLine("s2 = {0}", s2);
Console.WriteLine();
// Test these strings for equality.
Console.WriteLine("s1 == s2: {0}", s1 == s2);
Console.WriteLine("s1 == Hello!: {0}", s1 == "Hello!");
Console.WriteLine("s1 == HELLO!: {0}", s1 == "HELLO!");
Console.WriteLine("s1 == hello!: {0}", s1 == "hello!");
Console.WriteLine("s1.Equals(s2): {0}", s1.Equals(s2));
Console.WriteLine("Yo.Equals(s2): {0}", "Yo!".Equals(s2));
Console.WriteLine();
}
The C# equality operators perform a case-sensitive, character-by-character equality test on string
objects. Therefore, "Hello!" is not equal to "HELLO!", which is also different from "hello!". Also, keeping
the connection between string and System.String in mind, notice that we are able to test for equality
using the Equals() method of String as well as the baked-in equality operators. Finally, given that every
string literal (such as "Yo") is a valid System.String instance, we are able to access string-centric
functionality from a fixed sequence of characters.
99