How to Escape a Double Quote in a Verbatim String Literal

How do I escape in verbatim string?

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.

Can I escape a double quote in a verbatim string literal?

Use a duplicated double quote.

@"this ""word"" is escaped";

outputs:

this "word" is escaped

Escape double quotes in a string

No.

Either use verbatim string literals as you have, or escape the " using backslash.

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

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.

How I can escape a double quote in a verbatim string that contains variables

Using @poke suggestion I managed to get it work with placing a double quote and @ in the line:

    int teacherId = sqlStatus = (int)sqlCmd.LastInsertedId;
sqlCmd.CommandText = @"INSERT INTO report (report_type, report_date, semester, report_details, teacher_id)
VALUES (0, ""2018-01-01"", 1, '{
""teacherId"": "" " + teacherId.ToString() + "," +
@" ""mahderDate"": """",
""teacherShool"": """",
""baladia"": """",
""wilaya"": """",
""moufatecheReport"": """"
}'," + teacherId + ");";

Escaping verbatim string literals

The problem is that not all the strings you are concatenating are verbatim string literals, only the first portion of the concatenation is.

In other words,

@"SELECT value1, '"

is the only verbatim literal in the entire statement to build the final string.

You would need to add @ in front of the rest of your strings to make them all verbatim.

Which would make it look like:

String formLookupPull = @"SELECT value1, '"+tableName+ @"', '"+columnName+ @"' FROM lkpLookups WHERE ""table"" = '" + tableName + @"' and ""field"" = '" + columnName + @"';";

Why C# requires two double-quotes to print in case of verbatim string?

So technically, string s=@""Hello""; should print "Hello"

No, that would just be invalid. The compiler should - and does - obey the rules of the language specification.

Within a verbatim string literal, double-quotes must be doubled (not tripled) to distinguish them from the double-quote just meaning "the end of the string".

It's easiest to see this if you use a double-quote within the middle of a string, not at the start or end:

string x = @"start "" end";

F# works perfectly in the above case

Not as far as I can see. In a sample F# project in VS2015 Preview:

let x = @""Hello""

... gives an error, whereas @"""Hello""" results in a string of "Hello".

Additionally, the F# verbatim string literal documentation suggests it works exactly as per C#:

If preceded by the @ symbol, the literal is a verbatim string. This means that any escape sequences are ignored, except that two quotation mark characters are interpreted as one quotation mark character.

Basically, it sounds like verbatim string literals work in both C# and F# perfectly well, with both of them requiring double-quotes to be doubled. F# also has tripled-quoted strings, within which they don't need to be doubled... but that's just a separate feature that C# doesn't have.

EDIT: To answer your comment about ambiguity, you gave an example of @"1"2"". Let me change that very slightly:

string x = @"1"+"";

In C# at the moment, that means the concatenation of a verbatim string literal with content 1 and an empty regular string literal. If you're proposing that it should actually be a single verbatim string literal with content 1"+", with the parser relying on the quote directly before the next semi-colon being the end of the verbatim string literal, that strikes me as a really bad idea. For example, suppose I want to use a verbatim string literal as the first argument in a two-argument method call, like this:

Console.WriteLine(@"Foo {0}", "Bar");

By your rules, that would be a call with a single argument - it would be impossible to represent the call we're trying to make, as a single statement. (You'd need to use a variable for the verbatim string literal to avoid it messing things up.)

In short, I'm happier with the way C# already works.

How To Escape Quotation Marks in Multiple Line Of String? C#

To escape double quotes in a verbatim string (ie, a string declared with the @ prefix), simply double the quotes up (""). This is in contrast to how you would normally escape a double quote in a string, \".

var stringHolder = @" book book ""book""
ten ten ""book"" book pen
pen ""hook book"" dook
beer poor ""111"" cat map";
Console.WriteLine(stringHolder);
/*Output:
book book "book"
ten ten "book" book pen
pen "hook book" dook
beer poor "111" cat map
*/

When the indentation matters, you may have to fight the normal tabbing in your editor a bit, which can lead to some odd looking declarations.

namespace MyNamespace {
public class Foo {
public string GetString() => @"Hello
World"; // Returns a string that looks like
// Hello
// World

public string GetString2() => @"Hello
World"; // Returns a string that looks like
// Hello
// World
}
}

Verbatim string literals v escape sequences

Any difference here is limited strictly to the compiler; the IL and runtime have no concept of verbatim vs escaped - it just has the string.

As for which to choose: whichever is more convenient ;p I almost always use verbatim string literals if there are unusual characters, as that allows for multi-line strings very easily and visually.

As an interesting case:

bool areSame = ReferenceEquals("c:\\somewhere", @"c:\somewhere"); // true

which tells are they are exactly the same string instance (thanks to "interning"). They aren't just equivalent; they are the same string instance to the runtime. It is therefore impossible that they can be (to the runtime) different in any way.



Related Topics



Leave a reply



Submit