Fundamentals of Characters and Strings
Characters are the fundamental building blocks of C# source code. Every program is composed of characters that, when grouped together meaningfully, create a sequence that the compiler interprets as instructions describing how to accomplish a task. In addition to normal characters, a program also can contain character constants. A character constant is a character that is represented as an integer value, called a character code. For example, the integer value 122 corresponds to the character constant 'z'. The integer value 10 corresponds to the newline character ' '. Character constants are established according to the Unicode character set, an international character set that contains many more symbols and letters than does the ASCII character set (listed in Appendix F). To learn more about Unicode, see Appendix E.
A string is a series of characters treated as a unit. These characters can be uppercase letters, lowercase letters, digits and various special characters: +, -, *, /, $ and others. A string is an object of class string in the System namespace.[1] We write string literals, also called string constants, as sequences of characters in double quotation marks, as follows:
[1] C# provides the string keyword as an alias for class String. In this book, we use the term string.
"John Q. Doe" "9999 Main Street" "Waltham, Massachusetts" "(201) 555-1212"
A declaration can assign a string literal to a string reference. The declaration
string color = "blue";
initializes string reference color to refer to the string literal object "blue".
On occasion, a string will contain multiple backslash characters (this often occurs in the name of a file). To avoid excessive backslash characters, it is possible to exclude escape sequences and interpret all the characters in a string literally, using the @ character. Backslashes within the double quotation marks following the @ character are not considered escape sequences, but rather regular backslash characters. Often this simplifies programming and makes the code easier to read. For example, consider the string "C:MyFolderMySubFolderMyFile.txt" with the following assignment:
string file = "C:\MyFolder\MySubFolder\MyFile.txt";
Using the verbatim string syntax, the assignment can be altered to
string file = @"C:MyFolderMySubFolderMyFile.txt";
This approach also has the advantage of allowing strings to span multiple lines by preserving all newlines, spaces and tabs.