Question

I am a bit new to c#, and i am stuck at this point, I have a regular string, where i made use of \ to escape ", escape here means that to escape the compilers interpretation of ", and get " printed on the screen, and i get the expected output-->

class Program
{
    static void Main(string[] args)
    {
        string s1 = "This is a \"regular\" string";
        System.Console.WriteLine(s1);
        System.Console.Read();
    }
}

o/p--> This is a "regular" string

Now, i have a verbatim string, and i am trying to escape " using \ in the same manner as above..-->

class Program
{
    static void Main(string[] args)
    {
        string s2 = @"This is \t a \"verbatim\" string";//this would escape \t
        System.Console.WriteLine(s2);
        System.Console.Read();
    }
}

Why the above isn't working ?

Was it helpful?

Solution

Use a double quote:

 string s2 = @"This is \t a ""verbatim"" string";

OTHER TIPS

If you want to write a verbatim string containing a double-quote you must write two double-quotes.

string s2 = @"This is \t a ""verbatim"" string";

enter image description here

This is covered in section 2.4.4.5 of the C# specification:

2.4.4.5 String literals

C# supports two forms of string literals: regular string literals and verbatim string literals.

A regular string literal consists of zero or more characters enclosed in double quotes, as in "hello", and may include both simple escape sequences (such as \t for the tab character) and hexadecimal and Unicode escape sequences.

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.

In a Verbatim string, backslashes are treated as standard characters, not escape characters. The only character that needs escaping is the quotation marks, which you can escape using the very same character:

string s2 = @"This is \t a ""verbatim"" string";

Of course you can never add special characters like \t (tab) using this method, so it is only useful for simple strings - I think I only ever use this when working with file paths.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top