[String] Verbatim in C#
String Verbatim allows you to ignore escape sequences and makes writing strings more natural and readable. When using escape sequences in string literals, you sometimes make a mistake of typing \\ for the “backslash” and type \ instead. This will produce an error because the compiler will think that you are starting an escape sequence and it will read the next character after the \ and process it. If it doesn’t find a matching escape sequence, then it will issue an error.
Consider the following
example:
Answer with yes
o
Using String Verbatim to Ignore Escape Sequences
We use string verbatim
in certain situations where you don’t want your backslashes to trigger an
escape sequence. The syntax for string verbatim is simple. Just prefix the
string literal with the @ symbol.
I
want to have a cat\dog as a birthday present.
String verbatim is
commonly used when you are trying to output directories as a string. Because
directories contain a lot of backslashes, it would be justifiable to use string
verbatim rather than using a double backslash.
System.Console.WriteLine(@"C:\Some
Directory\SomeFile.txt");
C:\Some Directory\SomeFile.txt
If you want to print
double quotations, simply use two double quotations.
System.Console.WriteLine(@"Printing ""double
quotations""...");
Printing "double quotations"...
Avoid using string
verbatim and escape sequences at the same time as it will also print the escape
sequences in the output.
Using String Verbatim to Preserve Formatting of Strings
You can also use string
verbatim to print multiline strings without the user of \n escape sequence. For
example, if we are to print the following message:
C# is a great programming language and
Share this article with your friends
Post A Comment:
0 comments: