zee zee - 3 months ago 7
C# Question

Appending variable in a string

I am trying to insert variable in my string, but it is giving me Syntax error.

',' expected


Don't know what I am missing here. Below is what I am trying to do:

int var1 = 10;
string name = "somename";

string mystring = @"{ ""value"" : ""someval"", ""id"" : " + var1 + ", ""name"" : " + name + " }");


Expected Output:

{ "value" : "someval", "id" : "10", "name" : "somename"}

Answer

I guess this is what you wanted:

int var1 = 10;
string name = "somename";

string mystring = @"{ ""value"" : ""someval"", ""id"" : """+ var1 + @""" , ""name"" : """+ name + @"""}";
Console.WriteLine(mystring);
Console.ReadKey();

Output:

{ "value" : "someval", "id" : "10", "name" : "somename"}