Verbatim strings in C#: How to use of @ symbol in string

A verbatim string is one that does not need to be escaped which makes it easy to write, for example, a fully qualified file path like c:\myfolder\myfile.txt. This file path string can also created as verbatim string. Verbatim strings are those who started with @ symbol.

If you don’t use @ verbatim character, you need to write the file path as:

string myFileName = "C:\\myfolder\\myfile.txt";

But if you make this as verbatim strings, you can write this as:

string myFileName = @"C:\myfolder\myfile.txt";

Compilers understand this type of string as verbatim. Basically @ symbol tells the string constructor to ignore escape character and line breaks.

To include a double quotation mark in an @-quoted string,you will write this:

@"""Hi!"" you are welcome." // "Hi!" you are welcome.

Verbatim strings preserve new line characters as part of the string text, they can be used to initialize multiline strings. Use double quotation marks to embed a quotation mark inside a verbatim string. See the following example:

string text = @"You can find developer resources,code sample,
   articles,blogs,project sample for creating 
   application in various technology such as c#, vb.net, java...";
/* Output:
You can find developer resources,code sample,
   articles,blogs,project sample for creating 
   application in various technology such as c#, vb.net, java...
*/

Let’s see a example where we are using a escape character in string.

 String Str1 = “”;
 Str1 = “\\MyServer\TestFolder\NewFolder”;

In above statement compiler gives an error of ‘Unrecognized escape sequence’ but if we write above code like this:

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

compiler generate output without error.

Now we take an another example:

There are two string str1 and str2:

String Str1 = "this is the \n test string";
String str2 = @”this is the \n test string;
Console.WriteLine(Str1);
Console.WriteLine(Str2);

Output of the str1 will be :

this is the
test string

output of the str2 will be:

this is the \n test string

In case of str2, compiler will not be processed \n during generate output. Both output are different and we can understand easily benefit of @ in strings in c sharp language. The main benefit of this symbol is that string will not processed escape character like \n or \t.

Verbatim strings literals are often useful when you are dealing with filenames with path and regular expressions in your code, because backslashes in these types of strings are common and would need to be escaped if a regular string literal were used.

Suppose you want to use regular expression for matching ‘yyyy-mm-dd’ date format, you can write as below in C#.

string text = "2017-2-33"
string regexPattern = @"\d{4}-[01]\d-[0-3]\d"
Regex r = new Regex(pat, RegexOptions.IgnoreCase);
 
// Match the regular expression pattern against a text string.
Match m = r.Match(text);