views:

88

answers:

3

I bet that's an easy question for you, but searching SO or Google with { or } in the search string doesn't work very well.
So, let's say i wanna output {Hello World}, how do i do this using string.format(...)?

Edit:
looks like this:

string hello = "Hello World";
string.format("{0}", '{' + hello + '}');

would do the job, but that doesn't look very elegant to me. Is there a way to escape these characters inside the format string?

+11  A: 

Use {{ and }}. So your example would be string.Format("{{Hello World}}");

Rory
This seems to be similar to the printf convention in C++, using %% if one % is wanted in the output. Any reason why they didn't use the backslash escape character (which is used in C++ to escape quotes, double quotes, backslashes, ...)? Just curious.
Patrick
@Patrick: It appears that it's because it *already* has a use in that context: http://msdn.microsoft.com/en-us/library/0c899ak8.aspx#SpecifierEscape
Noon Silk
@Patrick: Probably to induce mass confusion and panic. Seriously though, I'm not sure, but you'd have to use multiple backslashes or it'd end up as a character escape ("\{" gives a compiler error because its not a valid escape, "\\" gives a single backslash, so you'd need something like "\\\\{" which is a bit much...)
Rory
@Patrick: the backslash is a compile-time escape char. But the interpretation of { } is at runtime. So while they could have use (double) backslashes that would have been no cleaner or easier than the current choice.
Henk Holterman
Thanks, Silky. Something learned today.
Patrick
For the reference of it all :)http://msdn.microsoft.com/en-us/library/txafckwd.aspx
cyberzed
Indeed, I think that the difference between compile-time interpretation and run-time interpretation is the real reason why it's different. Sorry I can't give +2 to you Henk.
Patrick
That would be `string.Format("{{{0}}}", hello);`. Oh, my.
Kobi
Ah ... ok, i tried "{{0}}" which outputed "{0}", but "{{{0}}}" works great. Thanks
Marcel Benthin
A: 

I had this same problem two weeks ago. Resharper solves it automatically.

Putting it as "{" + mystring + "}" and using the "use format string" automatically converted it to string.format("{{{0}}}", mystring).

Carra
nice feature ("3 more to go..")
Marcel Benthin
A: 

You might find

var hello = "Hello world";
var test = string.Format("{0}{1}{2}", "{", hello, "}");

easier to read than

var test = string.Format("{{{0}}}", hello);
Jonas Elfström