How to generically format a boolean to a Yes/No string?
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());
Unfortunately, Boolean.ToString(IFormatProvider) does not help here:
The provider parameter is reserved. It does not participate in the execution of this method. This means that the Boolean.ToString(IFormatProvider) method, unlike most methods with a provider parameter, does not reflect culture-specific settings.
In any case, Booleans represent True and False, not Yes and No. If you want to map True -> Yes and False -> No, you will have to do that (including localization) yourself; there's no built-in support in the framework for that. Your propopsed solution (Resources.Yes/No) looks fine to me.
in my razor page is working this:
@(item.Active.GetValueOrDefault() ? "Yes" : "No")
here is important if attribute is required (nullable) or not, if is required it should be good with:
@(item.Active ? "Yes":"No")
I found this here on some other post, just replaying, hope it helps some1.
As the other answers indicate, the framework does not allow boolean values to have custom formatters. However, it does allow for numbers to have custom formats. The GetHashCode method on the boolean will return 1 for true and 0 for false.
According to MSDN Custom Numeric Format Strings, when there are 3 sections of ";" the specified format will be applied to "positive numbers;negative numbers;zero".
The GetHashCode method can be called on the bool value to return a number so you can use the Custom Numeric Format String to return Yes/No or On/Off or any other set of words the situation calls for.
Here is a sample that returns on/OFF:
var truth = string.Format("{0:on;0;OFF}", true.GetHashCode());
var unTruth = string.Format("{0:on;0;OFF}", false.GetHashCode());
returns:
truth = on
unTruth = OFF