Search code examples
c#stringdouble-quotes

How can I escape double quotes in a string?


How can I escape double quotes in a string?

I tried:

@"He said to me, ""Hello World"". How are you?"

This worked -- "" becomes ".

Is there a C# function or other method to escape double quotes so that no changing in string is required?


Solution

  • Yes, you can escape the " using a backslash:

    string test = "He said to me, \"Hello World\" . How are you?";
    

    Otherwise you have to use verbatim string literals as you have.

    The string has not changed in either case - there is a single escaped " in it. This is just a way to tell C# that the character is part of the string and not a string terminator.