Search code examples
c#.netstringescapingverbatim-string

How do I escape " in verbatim string?


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 ?


Solution

  • Use a double quote:

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

    With C# 11 you could also use a raw string literal, for example:

    string longMessage = """
        This is a long message.
        It has several lines.
            Some are indented
                    more than others.
        Some should start at the first column.
        Some have "quoted text" in them.
        """;
    

    Raw string literals are a new format for string literals. Raw string literals can contain arbitrary text, including whitespace, new lines, embedded quotes, and other special characters without requiring escape sequences. A raw string literal starts with at least three double-quote (""") characters. It ends with the same number of double-quote characters.