CultureTypes.AllCultures includes all cultures

This may seem obvious, but it’s a lesson we had to learn the hard way.

A routine in our code attempted to find the best culture on the system that matched a certain language code. We implemented this by enumerating all cultures returned from CultureInfo.GetCultures(CultureTypes.AllCultures).

When checking the returned CultureInfo objects, the routine used the CultureInfo.Name property, which is documented as being a “culture name in the format languagecode2-country/regioncode2”. Part of our code required it to be a valid RFC 4646 language name, but didn’t actually support the full variety of tags specified in that RFC; specifically the “variant” part wasn’t handled correctly.

All the cultures installed by default on Windows have simple names (which passed our test), but users and programs are allowed to install custom cultures. These are, of course, returned when you request “AllCultures”. It turns out that Nokia PC Suite installs a culture named “tl-PH-Nokia”; this is a well-formed tag, but exposed the bug in handling the “variant” component in our code. (Even if the code were fully RFC 4646-compliant, the CultureAndRegionInfoBuilder that creates new cultures allows culture names forbidden by RFC 4646.)

Be aware that if you’re calling CultureInfo.GetCultures, a user’s system may well return more cultures than your development system.

Posted by Bradley Grainger on December 21, 2009