Maximus Decimus
Maximus Decimus

Reputation: 5271

Explaining confusing conditional string format

An ex-coworker wrote this:

String.Format("{0:#;;} {1:records;no records;record}", rows, rows - 1);
//Rows is a integer value

I read articles like these

Code Project - Custom String Formatting in .NET
MSDN - Custom Numeric Format Strings

But I don't still get it how that format works. Obviously I can see the output but I don't understand this part {0:#;;} and the second one. I want to do the same thing for specifying ages (year, years...)

I'm very curious about this string format. Can someone can explain this behavior? The author does not work with us anymore.

Upvotes: 8

Views: 501

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500675

This is a custom numeric format string, basically - but a pretty odd one, to be honest. In fact, it's two of them:

#;;
records;no records;record

In each case, you've got three sections, due to having two section separators (the semi-colons):

The first section applies to positive values, the second section applies to negative values, and the third section applies to zeros.

Your situation is further complicated by the developer using rows - 1 as the value to be formatted by the second format string, so it's really:

  • records if rows is greater than 1 (so rows - 1 is positive)
  • no records if rows is equal to 0 (so rows - 1 is negative)
  • record if rows is equal to 1 (so rows - 1 is zero)

And the first format string only includes the value of rows (due to the #) if rows is positive. So the overall result is:

Rows     Result
   2     2 records  (ditto for other values greater than 1)
   1     1 record
   0     no records

Personally I would have either used a conditional operator for that, or if/else statements - using a custom numeric format string is "clever" in the worst way...

Upvotes: 10

Related Questions