Surendra Sharma

Surendra Sharma

Search This Blog

Friday, March 27, 2015

How to include or put or embed curly braces in string.Format in C#

I was writing a HTML style within my repeater from code behind page as below

string s = string.Format("<style>.splashImg{0} { background-image:url({1}  );}</style>", 3, " myimage.jpg");

So that my final output should be like

<style>.splashImg3{ background-image:url(myimage.jpg);} </style>

And OMG I received error “Unrecognized escape sequence”. My first reaction was WTF what’s wrong with this code line. After careful look I come to know that it’s a problem of curly braces “{ }“.

As we are specifying curly braces for placeholder like {0} {1}, compiler is confused with other braces like “splashImg3{“.

So simplest solution is just write double braces for non-placeholder braces like “{{“ as shown in yellow color. So final code looks like

string s = string.Format("<style>.splashImg{0} {{ background-image:url( {1}  );}}</style>", 2, "myimage.jpg");


Please leave your comments or share this code if it’s useful for you.

No comments:

Post a Comment