Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a verbatim string? [duplicate]

Tags:

c#

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?

like image 425
Marc Avatar asked May 19 '13 13:05

Marc


People also ask

What are verbatim strings?

In C#, a verbatim string is created using a special symbol @. @ is known as a verbatim identifier. If a string contains @ as a prefix followed by double quotes, then compiler identifies that string as a verbatim string and compile that string.

How do you define a string literal as a verbatim string instead of a quoted string?

To use a verbatim string literal, you code an @ sign before the opening quote for the string. Then, you can enter backslashes, tabs, and new line characters between the opening and closing quotes. For example, you can use the Enter key to enter one or more new line characters.

How do you escape a string in C#?

C# includes escaping character \ (backslash) before these special characters to include in a string. Use backslash \ before double quotes and some special characters such as \,\n,\r,\t, etc. to include it in a string.

What does the at symbol do in C#?

To enable C# keywords to be used as identifiers. The @ character prefixes a code element that the compiler is to interpret as an identifier rather than a C# keyword. The following example uses the @ character to define an identifier named for that it uses in a for loop.


1 Answers

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""."
like image 67
pascalhein Avatar answered Oct 06 '22 18:10

pascalhein