Escape Sequences and Verbatim Strings in C#

posted on Monday, December 29, 2008 12:30 PM

C# uses special escape sequences within a string to signify that what follows is to be treated differently.  The special character is the backslash \.  This character says to treat whatever follows it as though it were part of the string itself. 

string msg = "Spot the dog said: \" get that dog bone\"";  // knowing this the following is good syntax:

Spot the dog said: "get that dog bone" //output

List of C# Escape Sequences

\"  Display a double quotation mark
\'   Display a single quotation mark.
\\  Display a backslash.
\0  Null (non-printing).
\a  Alarm (beep terminal alarm).
\b  Backspace (back up one character position).
\f   Form feed (advance to next page).
\n  Newline (advance to next line).
\r  Carriage return (move to left margin).
\t  Tab (advance one tab space, often eight characters).
\v  Vertical tab.


C# provides a way to avoid 'escaping' characters in strings.  You can use the verbatim string literal character @ to tell VS.NET to build the string exactly as it appears.
string msg = @"go to c:\temp"; // this would work

The verbatim string can be used to allow a single string to span more than one line i.e.

string msg = @"this is great
                        to be under
                        the sun";

category: .NET Language Features

Comments


No comments posted yet.
Post Comment
Title *
Name *
Email
Url
Comment *
Please add 3 and 5 and type the answer here:

About Me

An engineer by training and a software developer at heart. My techniques and approaches meld engineering approaches with software technology.

Core to these principles is a systematic approach to the development of software with a strong lifecycle and process management emphasis through adoption of mature technologies.

Ten years designing heavy structural steel and concrete structures and 12 years in the software development profession have embedded strong project management and business knowledge in my approaches.

Subscribe to Rss Feed


Follow me on twitter @dyardy