11

From ReSharper, I know that

var v = @"something";

makes v something called a verbatim string. What is this and what is a common scenario to use it?

Marc
  • 12,706
  • 7
  • 61
  • 97
  • 3
    http://msdn.microsoft.com/en-us/library/vstudio/ms228362.aspx – SLaks May 19 '13 at 13:31
  • 2
    Paths are pretty much the only time I ever use verbatim strings. Resharper's recommendation to convert *all* string literals to verbatim strings seems silly to me. – Cody Gray - on strike May 19 '13 at 13:41
  • 1
    @CodyGray AFAIK, ReSharper only offers it as a tool (it doesn't suggest it), and only if the string contains a backslash, which makes more sense to me. – pascalhein May 19 '13 at 13:43

2 Answers2

18

In a verbatim string, escape sequences (such as "\n" for newline) will be ignored. This helps you type strings containing backslashes.

The string is also allowed to extend over multiple lines, for example:

var s = @"
line1
line2";

The string will appear the same way you typed it in your source code, with line breaks, so you don't have to worry about indents, newlines etc.

To use quotes inside a verbatim literal, you just double them:

@"This is a string with ""quotes""."
pascalhein
  • 5,700
  • 4
  • 31
  • 44
13

It means that special chars don't need to be escaped, since you informed the compiler to expect special characters, and to ignore them. A common use case might be to specify a connection string:

string sqlServer = @"SERVER01\SQL"; 

This is perfectly valid, as opposed to in normal use where the backslash would be considered an escape character.

KingCronus
  • 4,509
  • 1
  • 24
  • 49
  • 1
    For clarity (since I've just answered a question citing this) although this answer says "special chars don't need to be escaped", if your string includes a double-quote character, it still needs to be escaped by putting two in a row. – Richardissimo Apr 25 '18 at 05:26