How to convert boolean to localized string
Asked Answered
W

2

8

There is any way to convert a boolean value to a localized string. I have tried:

var x = true;

var culture = new CultureInfo("en-US")
x.ToString(culture) // returns True

culture = new CultureInfo("pt-BR")
x.ToString(culture) // returns True, expected Verdadeiro

Or should I start typing the switch now to end before 2020?

Willing answered 16/12, 2013 at 20:11 Comment(6)
Thats for converting from string to boolean, I want the other direction.Willing
Start typing, because it is for a reason that you must install a language pack in Windows before you can actually 'see' the other language.Yoicks
well, there is NumberFormat and Calendars for a lot of languages, why not Boolean string...Willing
If you don't want to type it all out then x ? "1" : "0" is the simplest solution you've got, which would be the most universal you can get I guess.Yoicks
Or should I start typing the switch now to end before 2020? Did you finish the switch? tic tac. 2020 is here :)Florey
@daniherrera Damn, need to find a way to use the lock down as an excuse to not delivering this at the next sprint...Willing
N
9

Well, start typing because it's documented behaviour :)

Boolean.ToString(IFormatProvider)

Remarks

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.

Nieberg answered 16/12, 2013 at 20:19 Comment(0)
P
0

As @Michal pointed out, this is the documented behavior.

If your system supports many languages, you must have some sort of i18 support. Use that to convert a boolean value to string. You can add an extension method like so:

public string ToLocalizedString(this bool b)
{
    return ...i18n version of true or false...
}
Premiership answered 16/12, 2013 at 20:33 Comment(2)
If you're going to write a code sample, you should make sure that it compiles and doesn't contain pseudo code.Absenteeism
But it's really trivial. Add a resource dictionary (plus resource dictionaries for cultures that you want to support) to the project, and return either Properties.Resources.True or Properties.Resources.False. The bool type supports passing IFormatProvider to the ToString method, but it's not used (it probably only exists to implement the IConvertible interface), and the function just returns the constant strings "True" or "False". (Source: decompilation of .NET Framework code.)Missilery

© 2022 - 2024 — McMap. All rights reserved.