Formatting/parsing for a specific culture redux

In recent blog post I detailed how creating a culture via the CultureInfo constructor could actually create a user-overridden culture–which could be completely different than the culture that you’ve requested by name.  Fortunately there’s a way of overriding the user override (apologies for overloading “override”) by supplying the boolean value “false” in a CultureInfo overload.

As Greg Beech commented, there’s another method to create a culture–System.Globalization.CultureInfo.CreateSpecificCulture.  This sounds like it does exactly what you might expect and creates a “specific” culture.  Unfortunately, this method too violates the principle of least astonishment and creates a culture that uses the user-overridden values when the culture name matches that of the user’s current culture.

CreateSpecificCulture does not, as far as I can tell, have an overload/alternative to you allow to to force a “specific” culture, so the problem is much worse with CreateSpecificCulture.  I’ve gone ahead and logged a bug for it on Connect:

In case you’re wondering why this is more serious, consider the following following block of code that formats a date value as text:

    System.Globalization.CultureInfo ci;

    String text;

    ci = System.Globalization.CultureInfo.CreateSpecificCulture(“en-us”);

    text = String.Format(ci, “{0:d}”, DateTime.Now);

And that text is transmitted to another application (or another session of the same application, e.g. serialization), potentially in another locale, to be parsed with the following block of code:

    System.Globalization.CultureInfo ci;

    ci = System.Globalization.CultureInfo.CreateSpecificCulture(“en-us”);

    String text = ReadRecord();

    DateTime now = DateTime.Parse(text, ci);

If either (or) the user’s current culture is set to “English (United States)” and they’ve overridden the currency format the short date (say from “M/d/yyyy” to “d/M/yyyy”) will randomly result in the wrong date.


Leave a Reply

Your email address will not be published. Required fields are marked *