How can brackets be escaped in using string.Format
. For example:
String val = "1,2,3"
String.Format(" foo {{0}}", val);
This example doesn't throw an exception, but outputs the string foo {0}
Is there a way to escape the brackets?
How can brackets be escaped in using string.Format
. For example:
String val = "1,2,3"
String.Format(" foo {{0}}", val);
This example doesn't throw an exception, but outputs the string foo {0}
Is there a way to escape the brackets?
Almost there! The escape sequence for a brace is
{{
or}}
so for your example you would use:Yes to output
{
instring.Format
you have to escape it like this{{
So this
will output
"foo {1,2,3}"
.BUT you have to know about a design bug in C# which is that by going on the above logic you would assume this below code will print {24.00}
But this prints {N}. This is because the way C# parses escape sequences and format characters. To get the desired value in the above case you have to use this instead.
Reference Articles String.Format gottach and String Formatting FAQ
Came here in search of how to build json strings ad-hoc (without serializing a class/object) in C#. In other words, how to escape braces and quotes while using Interpolated Strings in C# and "verbatim string literals" (double quoted strings with '@' prefix), like...
or you can use c# string interpolation like this (feature available in C# 6.0)
Please do not use string.Format. Currently there is a better way to formatting string that more understandable.