Share via

Doesn't C# support escape sequences when we use verbatim?

Shervan360 1,641 Reputation points
Sep 13, 2024, 7:42 PM

Hello,

I read "a verbatim string literal is prefixed with @ and does not support escape sequences."

I have two questions:

1- If C# doesn't support escape sequences when we use verbatim, so how can I use an escape sequence (""123"") despite having verbatim?

2- How can I rewrite the following example without verbatim?

Thank you

namespace ConsoleApp2
{
     internal class Program
     {
          static void Main(string[] args)
          {
               string xml = @"<customer id=""123""></customer>"; //true
               string xml2 = "<customer id=""123""></customer>"; //wrong
               Console.WriteLine(xml);
          }
     }
}
.NET
.NET
Microsoft Technologies based on the .NET software framework.
4,053 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,209 questions
0 comments No comments
{count} votes

Accepted answer
  1. P a u l 10,751 Reputation points
    Sep 14, 2024, 1:58 PM

    By "escape sequence" it's referring to special characters that you prefix with a backslash () to represent special characters:

    https://learn.microsoft.com/en-us/cpp/c-language/escape-sequences

    ""123"" is an escape sequence, but it's specific to verbatim string literals & not what that sentence was referring to.

    Note: the first example prints the verbatim string "\t" whereas the second prints the character that that escape sequence represents (tab):

    string value1 = @"\t";
    string value2 = "\t";
    Console.WriteLine(value1);
    Console.WriteLine(value2);
    

    If you want to avoid using a verbatim string you could escape using backslashes:

    string xml2 = "<customer id=\"123\"></customer>";
    

    To avoid adding a backslash before every literal double quote you could also use raw string literals:

    string xml2 = """<customer id="123"></customer>""";
    Console.WriteLine(xml2);
    

    See here: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/raw-string

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.