Multi-Culture Boolean TryParses


  • So I see that DateTime and Int have multi-cultural try parses.

    I don't see anything in the documentation that leads me to believe Boolean.TryParse is Multi-Cultural.

    Anyone know anything more about this?

    Also I guess there is no easy way to convert Yes/No to True/False Multi-Culturally without defining resources.

    Wednesday, April 19, 2017 7:09 PM

All replies

  • DateTime accepts an IFormatProvider. This isn't multi-cultural inasmuch that the culture determines the formatting of a date/time. Each culture defines the date/time and number formatting that it uses and this is what DateTime (and actually the integrals) use. This works because, in the case of numbers, there is only one set of values. For DateTime the culture defines the month names as strings and therefore a string comparison can be done. But the Parse methods don't truly support conversion to arbitrary values.

    So Boolean, and other types, do not support conversion to/from other languages. To implement this you'd have to provide the culture-specific wording for each value. Having said that .NET itself does have language packs for various languages but these are really for translating the English wording in the framework to the culture-specific format. However MSDN explicitly documents that the conversion is culture-insensitive.

    To implement this yourself you'd want to provide a resource assembly that contains the correct mappings (or use one that already exists). You can then write your own extension method and/or static class to do the translation between a Boolean true/false and the string equivalent.

    But note that Boolean.TryParse/Parse technically only handle true and false strings (case insensitive). Passing anything else (eg. yes, no, 1, 0) will fail. Most people create their own conversion routine to handle these extra cases.

    Michael Taylor

    Thursday, April 20, 2017 12:22 AM