101

I have a string "I want to learn "c#"". How can I include the quotes before and after c#?

1

8 Answers 8

201

Escape them with backslashes.

"I want to learn \"C#\""
3
  • The reference manual is helpful: msdn.microsoft.com/en-us/library/ms228362.aspx
    – S.Lott
    Aug 11, 2010 at 12:17
  • 2
    you cannot use multiple """ when formatting a string String.Format("<E><A KH=\"{0}\" ID=\"{1}\"/><C><T ID=\"{2}\" SID=\"{3}\"><L P=\"{4}\" N=\"{5}\" /></T></C></E>", params) will not work with multiple quotes. please use this answer that is marked correctly and get used to the habit of doing it.
    – New Bee
    Sep 4, 2014 at 7:09
  • @ANeves fair to say that @newbee is wrong and that there's a Working counter-example: string ok = string.Format(@"""{0}"" = {1}", "yes", true); but don't link to stupid irrelevant pictures that waste peoples' time. This is a technical site
    – barlop
    Aug 8, 2016 at 22:23
108

As well as escaping quotes with backslashes, also see SO question 2911073 which explains how you could alternatively use double-quoting in a @-prefixed string:

string msg = @"I want to learn ""c#""";

which results in:

I want to learn "c#"

1
  • I needed this in my replace logic. string nullHideDecimal = @"<HideDecimal i:nil=""true""/>"; and then dataContractXML = dataContractXML.Replace(nullHideDecimal, "<HideDecimal>0</HideDecimal>");
    – Ziggler
    Jan 27, 2016 at 19:56
30

I use:

var value = "'Field1','Field2','Field3'".Replace("'", "\""); 

as opposed to the equivalent

var value = "\"Field1\",\"Field2\",\"Field3\"";

Because the former has far less noise than the latter, making it easier to see typo's etc.

I use it a lot in unit tests.

0
17
string str = @"""Hi, "" I am programmer";

OUTPUT - "Hi, " I am programmer

0
6

Since .NET 7 you can use raw string literals, which allows to declare strings without escaping symbols:

string text = """
I want to learn "C#"
""";
Console.WriteLine(text); // Prints string 'I want to learn "C#"'

If string does not start or end with double quote you can even make it single line:

string text = """I want to learn "C#"!""";
4

Use escape characters for example this code:

var message = "I want to learn \"c#\"";
Console.WriteLine(message);

will output:

I want to learn "c#"

1

You can also declare a constant and use it each time. neat and avoids confusion:

const string myStrQuote = "\"";
-4

The Code:

string myString = "Hello " + ((char)34) + " World." + ((char)34);

Output will be:

Hello "World."

Not the answer you're looking for? Browse other questions tagged or ask your own question.