Detecting and Configuring Culture and Language

In this lesson, we will learn how to set up languages and cultures supported by an application, and how to select the more appropriate one for each request.

Modern application frameworks support cultures, instead of just languages. A culture is a wider concept than a language since it also involves the way numbers and dates are formatted.

Number/date+time formats may be different for cultures associated with the same language. For instance, in the United Kingdom dates follows the day/month/year pattern while in the United States they follow the month/day/year pattern. Therefore, cultures are tied, not only to specific languages but also to language-Country pairs.

According to international standards, we should name cultures with 5 character strings of the type “xx-XX”. In this case, “xx” is the two-character code of the language, while “XX” is the two-character code of the country. Language codes are always lower case, while country codes are always uppercase. For instance, the culture associated with the English of the Great Britain is named “en-GB”, while the English culture for the United States is named “en-US”.

Each culture has an “xx” two character parent culture that contains just its language part. Thus, for instance, the parent culture of both “en-US” and “en-GB” is “en”. The number/date+time settings of the “xx” culture are usually taken from a five-character culture that is assumed as a reference for the language. For instance, settings for the “en” culture are taken from the “en-US” culture assumed as a reference for the English language.

Cultures in .NET applications

In .NET, cultures are represented by instances of the CultureInfo class that is contained in the System.Globalization namespace. An instance for a specific culture can be created by passing the name for the desired culture to the CultureInfo constructor, as shown in the example below:

var enUsCulture = new CultureInfo("en-US");

The CultureInfo.InvariantCulture static property contains the invariant culture, that is, the culture used to represent dates and numbers within the code. The invariant culture coincides with the “en-US” culture.

.NET doesn’t associate a culture to the whole application, but to specific threads. This way multi threaded applications that simultaneously serve several users can associate a different culture to each user thread. More specifically, .NET associates two cultures to each thread, a Culture, and a UICulture. The thread Culture is the default culture for the transformation of date+time and numbers into strings and for their parsing. The thread culture UICulture is used to select culture-specific .resx files containing string content translated in the languages supported by the application. We will look at .resx files later in this chapter.

Culture and UICulture for the current thread are set as shown below:

Get hands-on with 1400+ tech skills courses.