3

It might sound weird, stupid or whatever, but I was curious about finding a "native" way to make the bool.TryParse(string s, out bool result) method invariant culture.

It of course works if the input to be parsed is "true" or "false" but it would always return false as the parsing result if something like "verdadero", "wahr" or "falso" would be passed.

I haven't found anything on the MSDN related to this, but is there any way to make that bool.TryParse InvariantCulture'd?

Gonzo345
  • 1,133
  • 3
  • 20
  • 42
  • 2
    It's already "tied" to the Invariant Culture, the only two recognized values are `Boolean.TrueString` and `Boolean.FalseString`. Do you need an hypotetical `Parse()` method which accepts **localized** string values? You have to write it by your own... – Adriano Repetti Aug 22 '18 at 09:09

2 Answers2

2

A funny approach could be this. I found this nice piece of translation code:

public static string TranslateText( string input, string languagePair)
{
    string url = String.Format("http://www.google.com/translate_t?hl=en&ie=UTF8&text={0}&langpair={1}", input, languagePair);
    HttpClient httpClient = new HttpClient();
    string result = httpClient.GetStringAsync(url).Result;
    result = result.Substring(result.IndexOf("<span title=\"") + "<span title=\"".Length);
    result = result.Substring(result.IndexOf(">") + 1);
    result = result.Substring(0, result.IndexOf("</span>"));
    return result.Trim();
}

on this answer

You could use it like this:

bool output;

Boolean.TryParse(TranslateText("wahr", "de|en"), out output);
Console.WriteLine($"German Output: {output}");

Boolean.TryParse(TranslateText("verdadero", "esp|en"), out output);
Console.WriteLine($"Spanish Output: {output}");

Boolean.TryParse(TranslateText("falso", "it|en"), out output);
Console.WriteLine($"Italian Output: {output}");

It gives you the following output:

German Output: True
Spanish Output: True
Italian Output: False

Its more of a playfull approach. ;)

EDIT:

For this purpose you could also use System.Globalization.CultureInfo.CurrentCulture

Boolean.TryParse(TranslateText("wahr", System.Globalization.CultureInfo.CurrentCulture + "|en"), out output);
Console.WriteLine($"{System.Globalization.CultureInfo.CurrentCulture} Output: {output}");
Boolean.TryParse(TranslateText("falsch", System.Globalization.CultureInfo.CurrentCulture + "|en"), out output);
Console.WriteLine($"{System.Globalization.CultureInfo.CurrentCulture} Output: {output}");

and it works actually! Output:

de-DE Output: True
de-DE Output: False

Mong Zhu
  • 23,309
  • 10
  • 44
  • 76
0

If you are really worried about Invariant culture issue you can first try to convert it

string sNew = s.ToString(CultureInfo.InvariantCulture);

bool.TryParse(string sNew, out bool result)
Mong Zhu
  • 23,309
  • 10
  • 44
  • 76
ManishM
  • 583
  • 5
  • 7