user1990395
user1990395

Reputation: 185

String.Format in Double Quotes in C#

Is anybody can help me with string.Format for below line. In '2056' I need to pass as {0}.

string body = @"{""idTimeSerie"":""2056"",""idTso"":-1}";

Due to double quotes I can't get it to execute.

I've tried in this way but no success.

string body = string.Format
                    (@"{""idTimeSerie"": "" \"{0}\" "",""idTso"":-1}", countryID);

Upvotes: 4

Views: 6082

Answers (4)

aked
aked

Reputation: 5835

you have to escape the curly braces

replace { to {{

string body = @"{{""idTimeSerie"":""2056"",""idTso"":-1}}";

Edit : From MSDN - Another way of Escaping

Opening and closing braces are interpreted as starting and ending a format item. Consequently, you must use an escape sequence to display a literal opening brace or closing brace. Specify two opening braces ("{{") in the fixed text to display one opening brace ("{"), or two closing braces ("}}") to display one closing brace ("}"). Braces in a format item are interpreted sequentially in the order they are encountered. Interpreting nested braces is not supported.

int value = 6324;
string output = string.Format("{0}{1:D}{2}", 
                             "{", value, "}");
Console.WriteLine(output);
// The example displays the following output: 
//       {6324}

Upvotes: 4

allonhadaya
allonhadaya

Reputation: 1297

Try this:

string body = string.Format(@"{{ ""idTimeSerie"": ""{0}"", ""idTso"": -1 ", countryID) + "}";

Explanation:

1) When using the @ flavor of string literals, double quotes are indicated by "" (two consecutive double quotes).

See MSDN:

@"""Ahoy!"" cried the captain." // "Ahoy!" cried the captain.

2) Use {{ and }} to indicate a literal { and } respectively in your string format.

See MSDN (Escaping Braces):

Specify two opening braces ("{{") in the fixed text to display one opening brace ("{"), or two closing braces ("}}") to display one closing brace ("}").

Upvotes: 2

Luiz Freneda
Luiz Freneda

Reputation: 112

You can do like this:

string body = string.Format("{{\"idTimeSerie\":\"{0}\",\"idTso\":-1}}", countryID);

Upvotes: 2

DGibbs
DGibbs

Reputation: 14618

Don't use a verbatim string in this case. I suspect you want:

string body = string.Format("{\"idTimeSerie\":\"{0}\",\"idTso\":-1}", countryID);

Upvotes: -1

Related Questions