C# String Theory—String literals

Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio


Jump to: navigation, search
CSharp-Online.NET:Articles
C# Articles

C# String Theory

edit

C# String literals

A C# string literal is a contiguous sequence of zero or more characters enclosed in double quotation marks (") representing string data, rather than a reference to string data. A string literal is a literal of type string hard-coded in your program.

There are two methods of representing string literals—literal (quoted) and verbatim (@-quoted). The literal method requires certain characters such as quotation marks (") and whitespace to be escaped—that is, preceded by the backslash (\) escape character. On the other hand, the verbatim method accepts any characters—except quotation marks—including whitespace without escaping.

To use the literal method, simply enclose the string literal in quotation marks. To use the verbatim method, use the quotation marks, but prefix the opening quotation mark with the at sign (@). An advantage of the verbatim method is that escape sequences are not processed making it easy to write—for example—a regular expression or a fully qualified file name. In the following example, the literal string must escape the backslashes, while the verbatim string needs no escapement.

string literal  =  "C:\\Documents\\csharp-online.net\\";
string verbatim = @"C:\Documents\csharp-online.net\";

To include a double quotation mark (") in a literal string, escape it, i.e. "\"". In a verbatim string, double it, i.e. """".

string string1 = @"""Mr. Watson. Come Here. I need you."", cried Bell.";

The @ symbol is, also, used to reference (/reference) identifiers that happen to be C# keywords, e.g. @switch.

The escape code \uhhhh—where hhhh is a four digit number—represents the Unicode character U+hhhh. Eight digit Unicode escape codes are also recognized.

string string1 = "\u0048ello,";
string string2 = " World!";
Console.WriteLine (string1 + string2 == "Hello, World!"); // true 

A complete list of C# string literals is available in Appendix B. C# String Literals


Multiline String literals

The following example illustrates two ways of creating multiline string literals:

string couplet1 = "It matters not how strait the gate,\n"
                + "How charged with punishments the scroll,";
string couplet2 = @"I am the master of my fate:
I am the captain of my soul.";

Visual C# Best Practices

  • Avoid using the @ symbol in order to use C# keywords as identifiers. It can obfuscate the code making it difficult to read and is just plain, poor practice.


Previous_Page_.gif Next_Page_.gif

Personal tools