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.

1

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

9 Comments

I...wait...what? EDIT...thanks for explaining further
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).
@CalvinSmith: I've edited it further - this may help.
@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...
@CalvinSmith: Yes, certain situations like hating your colleagues with a passion ;) I agree it's interesting though.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.