Unable to string.Format a C# multiline verbatim string when escaping curly braces

264 Views Asked by At

I am having issue with String.Format on a verbatim string with escaped curly braced.

It's raising a FormatError() Exception:Message: System.FormatException : Input string was not in a correct format.

    String s = $@"{{ ""ver"": ""1.0"",""userId"": ""{0}""}}";
    String.Format(s, "1234")
1

There are 1 best solutions below

0
Aleks On BEST ANSWER

You are using the C# string interpolation special character "$", however, you are using positional parameters in your template.

It should be:-

String s = @"{{ ""ver"": ""1.0"",""userId"": ""{0}""}}";

String.Format(s, "1234").Dump();

Or just:-

var userId = 1234;

String s = $@"{{ ""ver"": ""1.0"",""userId"": ""{userId}""}}";

If your intention is to generate JSON output, a more appropriate method would be to create your object and serialize it using the Newtonsoft.Json package:-

var x = new
{
    ver = "1.0",
    userId = "1234"
};

var s = JsonConvert.SerializeObject(x);