tags:

views:

1511

answers:

5

I saw a code snippet the other day that converts a Boolean value to the corresponding "Yes"/"No" value:

CDbl(True).ToString("Yes;Yes;No")

The code works fine but I'm curious how it works and I haven't been able to find the answer in the MSDN documentation for ToString().

Can anybody shed some light on this?

+9  A: 

Take a look here and here, for official documentation. And this great cheatsheet from Jhon Sheehan's Blog!

tanathos
More specifically from the mentioned cheatsheet: "; Section separator The ';' character is used to separate sections for positive, negative, and zero numbers in the format string."
Arjan Einbu
Jhon Sheehan's cheatsheet is money!
Chuck Conway
+2  A: 

It's using the literal format string from the customized numeric format strings. You can supply a literal that maps onto numbes that are postive, negative, or zero numbers. The first "yes" maps to positive, the second to negative, and the "no" to zeros. Thus any non-zero is yes, and only zeros are no. This is equivalent to standard true/false semantic interpretations on numeric values.

Look under "section separator" of the Custom Numeric Format strings page.

tvanfosson
+5  A: 

It's treating it as a Custom Numeric Format String. Specifically, see the part about section separators in the linked page:

The ';' character is used to separate sections for positive, negative, and zero numbers in the format string. If there are two sections in the custom format string, the leftmost section defines the formatting of positive and zero numbers, while the rightmost section defines the formatting of negative numbers. If there are three sections, the leftmost section defines the formatting of positive numbers, the middle section defines the formatting of negative numbers, and the rightmost section defines the formatting of zero numbers.

Joel Coehoorn
+1  A: 

As @Joel Coehoorn and @tvanfosson said, it's using a custom numeric format string. The reason it works is that a boolean value is convertible to a double using the following (essentially):

public static double ToDouble(bool value)
{
    return (value ? ((double) 1) : ((double) 0));
}

So, if value is true, it returns 1 and if value is false it returns 0. At that point, the section mapping rules apply as described by @tvanfosson (and subsequently @Joel Coehoorn).

Scott Dorman
+1  A: 

Steve-X has the best documentation for String.Format I've seen so far: Steve-X ToString()

I know you asked for "ToString", but ToString is dependent to the implementation you are calling (i.e. DateTime.ToString(), decimal.ToString...etc).

If you are really interested in how it works bust open reflector and peruse the code.

Chuck Conway