92

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

one noa
  • 346
  • 1
  • 3
  • 10
learning
  • 10,935
  • 33
  • 85
  • 154
  • 2
    possible duplicate of [How can I put quotes in a string?](http://stackoverflow.com/questions/2911073/how-can-i-put-quotes-in-a-string) – Oliver Aug 11 '10 at 12:18

7 Answers7

184

Escape them with backslashes.

"I want to learn \"C#\""
kennytm
  • 491,404
  • 99
  • 1,053
  • 989
  • The reference manual is helpful: http://msdn.microsoft.com/en-us/library/ms228362.aspx – S.Lott Aug 11 '10 at 12:17
  • 2
    you cannot use multiple """ when formatting a string String.Format("", 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 04 '14 at 07: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 08 '16 at 22:23
97

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#""";
Community
  • 1
  • 1
NeilDurant
  • 1,982
  • 1
  • 13
  • 14
  • I needed this in my replace logic. string nullHideDecimal = @""; and then dataContractXML = dataContractXML.Replace(nullHideDecimal, "0"); – Ziggler Jan 27 '16 at 19:56
25

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.

Mdev
  • 2,434
  • 2
  • 16
  • 24
James Cochrane
  • 259
  • 3
  • 3
15
string str = @"""Hi, "" I am programmer";

OUTPUT - "Hi, " I am programmer

Bhargav Rao
  • 45,811
  • 27
  • 120
  • 136
somesh
  • 3,388
  • 4
  • 15
  • 10
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#"

Łukasz W.
  • 9,289
  • 5
  • 35
  • 61
1

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

const string myStrQuote = "\"";
Chagbert
  • 692
  • 6
  • 14
-4

The Code:

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

Output will be:

Hello "World."

Matthew Verstraete
  • 5,958
  • 21
  • 63
  • 113
Ariel Terrani
  • 568
  • 5
  • 6