Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generically format a boolean to a Yes/No string?

I would like to display Yes/No in different languages according to some boolean variable.
Is there a generic way to format it according to the locale passed to it?
If there isn't, what is the standard way to format a boolean besides boolVar ? Resources.Yes : Resources.No.
I'm guessing that boolVar.ToString(IFormatProvider) is involved.
Is my assumption correct?

like image 814
the_drow Avatar asked Apr 12 '11 09:04

the_drow


People also ask

How do you convert boolean to yes or no?

To convert a boolean value to Yes/No, use a ternary operator and conditionally check if the boolean value is equal to true , if it is, return yes , otherwise return no , e.g. bool === true ? 'yes' : 'no' . Copied! We used a ternary operator which is very similar to an if/else statement.

What is the format for boolean?

Format for boolean data type specified in Metadata consists of up to four parts separated from each other by the same delimiter. This delimiter must also be at the beginning and the end of the Format string. On the other hand, the delimiter must not be contained in the values of the boolean field.

How do you know if a boolean value is true?

To check if a value is of boolean type, check if the value is equal to false or equal to true , e.g. if (variable === true || variable === false) . Boolean values can only be true and false , so if either condition is met, the value has a type of boolean. Copied!


1 Answers

The framework itself does not provide this for you (as far as I know). Translating true/false into yes/no does not strike me as more common than other potential translations (such as on/off, checked/unchecked, read-only/read-write or whatever).

I imagine that the easiest way to encapsulate the behavior is to make an extension method that wraps the construct that you suggest yourself in your question:

public static class BooleanExtensions {     public static string ToYesNoString(this bool value)     {         return value ? Resources.Yes : Resources.No;     } } 

Usage:

bool someValue = GetSomeValue(); Console.WriteLine(someValue.ToYesNoString()); 
like image 64
Fredrik Mörk Avatar answered Sep 18 '22 13:09

Fredrik Mörk