Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this String.Format operation throw FormatException?

Tags:

c#

.net

I created a workaround for it, but was perplexed that the following string:

string dpicker = "<script>$(function() { $(\"#{0}\").datepicker();});</script>";

throws FormatException when performing this:

String.Format(dpicker, "DatePicker");

What is the actual problem?

like image 527
Cyberherbalist Avatar asked Apr 14 '26 02:04

Cyberherbalist


2 Answers

You need to escape the curly-braces for the function:

string dpicker = "<script>$(function() {{ $(\"#{0}\").datepicker();}});</script>";
//                                     ^^                          ^^

As used here, the correct way to do that is to double them up. See Escaping Braces.

The string.Format method works by looking through the entire string, character-by-character, and choosing whether they fall into the "literal" category, or the one for format arguments. As soon as it saw your unescaped curly-brace, it understood that to mean "we're formatting now," so it first looked for a numeric character (of course, that's not the only acceptable value there in the curly braces, but at least one digit must come first), couldn't find one, and threw the exception.

like image 186
Matthew Haugen Avatar answered Apr 15 '26 15:04

Matthew Haugen


String.Format was trying to interpret that first { as the start of a placeholder, and of course couldn't parse $(\"#{0}\").datepicker(); into some kind of numerical value. You can escape brackets in a format string by doing {{ and }}. So this code should work:

string dpicker = "<script>$(function() {{ $(\"#{0}\").datepicker();}});</script>";
var s = String.Format(dpicker, "DatePicker");
like image 34
nateirvin Avatar answered Apr 15 '26 16:04

nateirvin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!