How to escape braces in a format string in C#

HomeC#

How to escape braces in a format string in C#

Escape curly braces in an interpolated string in C#
Convert date string to DateTime object in C#
Case insensitive comparison in C#

Whenever we’re trying to add brackets in a string.Format command we need to escape them, so the problem is that we have

string val = "1,2,3";

And we want the output to be “foo {1, 2, 3}”, to be able to do this we can do the following :

string a = "1,2,3";
string b = String.Format(" foo {{{0}}}",t);

This will give the result we want, adding two braces before and after the braces that will contain the 0

Also since C# 6.0 string interpolation can be used to have the same result

string in = "1,2,3";
string out = $" foo {{{in}}}";

The output will also be “foo {1,2,3}”

COMMENTS

DISQUS: 0