Explaining confusing conditional string format
Asked Answered
M

1

8

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.

Metchnikoff answered 2/9, 2014 at 16:34 Comment(1)
The ";" Section SeparatorTurbojet
W
10

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...

Ware answered 2/9, 2014 at 16:39 Comment(9)
I...wait...what? EDIT...thanks for explaining furtherRankins
That a pretty clever usage of string format. It's also important, that only for positive values actual number will be printed (because of #;; in first format).Jamey
@CalvinSmith: I've edited it further - this may help.Ware
@MarcinJuraszek: Yes, but I'd use the words "pretty clever" in a derogatory sense in this case. This isn't code I'd want to actually see...Ware
@JonSkeet Thats true, but its also something I havent encountered in string.format and could be useful for certain situationsRankins
Sure. I totally agree. It's kind of abusing the BCL.Jamey
@CalvinSmith: Yes, certain situations like hating your colleagues with a passion ;) I agree it's interesting though.Ware
I'm tempted to memorise this for when being interviewed they ask if you have any questions; to wipe the smug look off their developers (knowitall) face :DCollaboration
see both Paul and John came up with awesome scenarios right away.Rankins

© 2022 - 2024 — McMap. All rights reserved.