#65 – Verbatim String Literals

Because the backslash (\) is the first character in an escape sequence, you need to use the double-backslash sequence (\\) to embed actual backslashes in a string literal.

 string file = "C:\\MyDir\\Another Dir\\thefile.txt";

Because this can get a little hard to read, C# allows using the at sign (@) character to indicate a verbatim string literal–a string literal in which escape sequences should not be interpreted.

Using a verbatim string literal, we can write the earlier string without doubling the backslashes:

 string file = @"C:\MyDir\Another Dir\thefile.txt";

We can also use a verbatim string literal to split a string across multiple lines in the source code, rather than embedding the \n escape sequence:

string file = @"First line
Second line
Third line";

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

3 Responses to #65 – Verbatim String Literals

  1. Bob says:

    @’s an ‘at symbol’ or ‘at’, &’s an ampersand…

  2. Pingback: #478 – Verbatim String Literals Can Span Multiple Lines « 2,000 Things You Should Know About C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: