Verbatim String: a string precede with a @ character (the at sign).

By lxcid

C# support 2 type of strings: regular string and verbatim string.

In this post we will try to explain what is a verbatim string.

An explanation of verbatim string in MSDN is:

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. A verbatim string literal may span multiple lines.

The MSDN explanation of  is clear cut enough but allow me to give you one example:

@"\w+([-.]\w+)*\@\w+([-.]\w+)*\.[A-Za-z]{2,4}$"

The above string is a regular expression for validating an email address.

Notice in the above string, I used the ‘\’ (escape) character quite a number of times. But a closer observation will prompt one questions: none of the escape sequence make sense. This is where the @ character preceding the string come handy. The @ character basically tell the compiler to ignore escape character in the string that follows.

Without the preceding @ character, the above regular expression string should be written as:

"\\w+([-.]\\w+)*\\@\\w+([-.]\\w+)*\\.[A-Za-z]{2,4}$"

Hope this helps.

Tags: , , , , , , , , , , , , , ,

Leave a Reply