AdBlock Detected

We provide high-quality source code for free. Please consider disabling your AdBlocker to support our work.

Buy me a Coffee

Saved Tutorials

No saved posts yet.

Press Enter to see all results

[String Verbatim] in C# - trickcode

By pushpam abhishek
Listen to this article

[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:

System.Console.WriteLine("I
want to have a cat\dog as a birthday present."); 


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.
System.Console.WriteLine(@"I want to have a cat\dog as a birthday present.");
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                        

Share this post

pushpam abhishek

About pushpam abhishek

Pushpam Abhishek is a Software & web developer and designer who specializes in back-end as well as front-end development. If you'd like to connect with him, follow him on Twitter as @pushpambhshk

Comments