Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Culture invariant bool.TryParse

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?

like image 403
Gonzo345 Avatar asked Dec 07 '25 10:12

Gonzo345


1 Answers

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

like image 187
Mong Zhu Avatar answered Dec 10 '25 00:12

Mong Zhu