Verbatim strings in C# - Use of @ symbol in string literals

A String can be created as a verbatim string. Verbatim strings start with @ symbol. The C# compiler understand this type of string as verbatim. Basically the @ symbol tells the string constructor to ignore escape characters and line breaks.

In this article we will understand use of the @ symbol in C# strings.

See here

String Str1 = "";

Str1 = "\\MyServer\TestFolder\NewFolder";

In statement above the compiler gives an error of 'Unrecognized escape sequence', but if we write the code like this:

str2 = @"\\MyServer\TestFolder\NewFolder";

the compiler does not generate an error.

Now we take an another example:

There are two strings, str1 and str2:

String Str1 = "";

String str2 = "";

Str1 = "this is the \n test string";

Output of the str1 is :

this is the

 test string

str2 = @"this is the \n test string";

In the case of str2, the compiler will not process the \n when generating the output.

this is the \n test string

The outputs are different and we can easily understand the benefit of @ in strings in the C# language.

The main benefit of this symbol is that escape characters such as \n and \t will not be processed.

Note: MSDN says that a verbatim string literal consists of an @ character followed by a double-quote character, zero or more characters, and a closing double-quote character. A simple example is @"hello". In a verbatim string literal, the characters between the delimiters are interpreted verbatim, the only exception being a quote-escape-sequence. In particular, simple escape sequences and hexadecimal and Unicode escape sequences are not processed in verbatim string literals.


Similar Articles