0

I've got a very strange problem. My C# interactive gives me:

> string.Format("{0:P1}", 0, CultureInfo.InvariantCulture)
"0.0%"

However, in the debugger, the same expression yields something else:

> string.Format("{0:P1}", 0, CultureInfo.InvariantCulture)
"0.0 %"

Does anybody have any ideas how this can happen?

chtenb
  • 14,924
  • 14
  • 78
  • 116
  • Most likely different runtimes. Experimentally the extra space is produced by .NET Framework, but not .NET Core. (Whether that's a bug or not is another matter. I can't find an announcement with a quick search, but I know there were some deliberate changes in Core in this regard.) – Jeroen Mostert Jun 21 '22 at 08:35
  • @JeroenMostert see my answer post – chtenb Jun 21 '22 at 08:46

1 Answers1

0

Ok, it seems I messed up the order of arguments. I should have

string.Format(CultureInfo.InvariantCulture, "{0:P1}", 0)

Apparently the compiler and runtime are fine with superfluous format arguments and will happily discard them for you.

The expressions in the OP will have used the Current Culture which may indeed have different semantics between framework and core as @JeroenMostert suggested.

chtenb
  • 14,924
  • 14
  • 78
  • 116
  • Oh that's neat. And this is why interpolated strings are just so much better. :P – Jeroen Mostert Jun 21 '22 at 08:47
  • `are fine with superfluous format arguments and will happily discard them` - yes, which is an [important feature](https://devblogs.microsoft.com/oldnewthing/20090810-00/?p=17163). – GSerg Jun 21 '22 at 08:51
  • @GSerg how does that classify as an important feature? xD – chtenb Jun 21 '22 at 08:59
  • @chtenb It allows you to pass more or less verbose template strings to a single `string.Format` call. Which is very handy not only for controlling your logging, but also for internationalization where for some languages you simply don't want some of the arguments. Imagine that wasn't the case and your program supported localizeable resources. For each invocation of `string.Format` you would need to first fetch the template string, correctly parse it for `{X}`s and then include a `switch` to call that template with the exact number of arguments that the current language's version expects. – GSerg Jun 21 '22 at 09:04