Skip to main content

Culture Information and Localization in .NET



Namespace: System.Globalization

CultureInfo Class:
                It provides information like the Format of numbers and dates, Culture’s Calendar, Culture’s language and sublanguage (if applicable), Country and region of the culture. The Basic use of CultureInfo class is shown here:

• How string Comparisons are performed
• How Number Comparison & Formats are performed
• Date Comparison and Formats.
• How resources are retrieved and used.

Cultures are grouped into three categories:

Invariant Culture: It’s Culture Insensitive. It can be used to build some trial application. It can be also used to build an application with hard-coded expiry date that ignores cultures. But using it for every comparison will be incorrect and inappropriate.

Neutral Culture: English(en), Frensh(fr), and Spanish(sp). A neutral culture is related to language but it’s not related to specific region or country. Overuse of the Neutral culture will also result in some inappropriate results.

Specific Culture: It’s the most precisely defined culture. It’s identified through the Neutral culture’s as prefix, a hyphen and a region or country specific abbreviation i.e. (en-us).


To obtain information at runtime about the current culture, one can use Thread.CurrentThread.CurrentCulture that represents an instance of the CultureInfo class.

Name
Description
ClearCachedData
Refreshes cached culture-related information.
Clone
Creates a copy of the current CultureInfo.
CreateSpecificCulture (Static)
Creates a CultureInfo that represents the specific culture that is associated with the specified name.
Equals
Determines whether the specified object is the same culture as the current CultureInfo. (Overrides .Equals(Object).)
GetConsoleFallbackUICulture
Gets an alternate user interface culture suitable for console applications when the default graphic user interface culture is unsuitable.
GetCultureInfo
Overloaded. Retrieves a cached, read-only instance of a culture.
GetCultureInfoByIetfLanguageTag (Static)
Retrieves a read-only CultureInfo object whose linguistic characteristics are identified by the specified RFC 3066(bis) language tag.
GetCultures(Static)
Gets the list of supported cultures filtered by the specified CultureTypes parameter.
GetFormat
Gets an object that defines how to format the specified type.
GetHashCode
Serves as a hash function for the current CultureInfo, suitable for hashing algorithms and data structures, such as a hash table. (Overrides .GetHashCode().)
GetType
Gets the Type of the current instance. (Inherited from Object.)
ReadOnly(Static)
Returns a read-only wrapper around the specified CultureInfo.
ToString
Returns a string containing the name of the current CultureInfo in the format "<languagecode2>-<country/regioncode2>". (Overrides .ToString().)

Public Properties
Name
Description
Calendar
Gets the default calendar used by the culture.
CompareInfo
Gets the CompareInfo that defines how to compare strings for the culture.
CultureTypes
Gets the culture types that pertain to the current CultureInfo object.
CurrentCulture(Static)
Gets the CultureInfo that represents the culture used by the current thread.
CurrentUICulture(Static)
Gets the CultureInfo that represents the current culture used by the Resource Manager to look up culture-specific resources at run time.
DateTimeFormat
Gets or sets a DateTimeFormatInfo that defines the culturally appropriate format of displaying dates and times.
DisplayName
Gets the culture name in the format "<languagefull> (<country/regionfull>)" in the language of the localized version of .NET Framework.
EnglishName
Gets the culture name in the format "<languagefull> (<country/regionfull>)" in English.
IetfLanguageTag
Gets the RFC 3066(bis) standard identification for a language.
InstalledUICulture(static)
Gets the CultureInfo that represents the culture installed with the operating system.
InvariantCulture(static)
Gets the CultureInfo that is culture-independent (invariant).
IsNeutralCulture
Gets a value indicating whether the current CultureInfo represents a neutral culture.
IsReadOnly
Gets a value indicating whether the current CultureInfo is read-only.
KeyboardLayoutId
Gets the active input locale identifier.
LCID
Gets the culture identifier for the current CultureInfo.
Name
Gets the culture name in the format "<languagecode2>-<country/regioncode2>".
NativeName
Gets the culture name in the format "<languagefull> (<country/regionfull>)" in the language that the culture is set to display.
NumberFormat
Gets or sets a NumberFormatInfo that defines the culturally appropriate format of displaying numbers, currency, and percentage.
OptionalCalendars
Gets the list of calendars that can be used by the culture.
Parent
Gets the CultureInfo that represents the parent culture of the current CultureInfo.
TextInfo
Gets the TextInfo that defines the writing system associated with the culture.
ThreeLetterISOLanguageName
Gets the ISO 639-2 three-letter code for the language of the current CultureInfo.
ThreeLetterWindowsLanguageName
Gets the three-letter code for the language as defined in the Windows API.
TwoLetterISOLanguageName
Gets the ISO 639-1 two-letter code for the language of the current CultureInfo.
UseUserOverride
Gets a value indicating whether the current CultureInfo uses the user-selected culture settings.

One can also use the formatting techniques to format the output for a specific culture.
 Usage:

CultureInfo ci = new CultureInfo("en-us");
double floating = 10761.937554;

floating.ToString("C", ci)   // Displays "C: $10,761.94"
floating.ToString("E03", ci) // Displays "E: 1.076E+004"
floating.ToString("F04", ci) // Displays "F: 10761.9376"
floating.ToString("G", ci)   // Displays "G: 10761.937554"
floating.ToString("N03", ci) // Displays "N: 10,761.938"
(floating/10000).ToString("P02", ci)); // Displays "P: 107.62 %"
floating.ToString("R", ci)   // Displays "R: 10761.937554"


Double myDouble = 1234567890;
String myString = myDouble.ToString( "(###) ### - ####" );
// The value of myString is "(123) 456 – 7890".

int  MyInt = 42;
MyString = MyInt.ToString( "My Number = #" );
// In the U.S. English culture, MyString has the value:
// "My Number = 42".

CultureInfo class also exposes another culture with property CurrentUICulture. It can be used for internal manipulations and calculation. CurrentUICulture can be only manipulated ones at the startup (usually in main method) to maintain application consistency and stability.

Defines the types of culture lists that can be retrieved using CultureInfo.GetCultures(CultureTypes).

AllCultures
All cultures that ship with the .NET Framework including neutral and specific cultures, cultures installed in the Windows system, and custom cultures created by the user.
FrameworkCultures
Neutral and specific cultures shipped with the .NET Framework.
InstalledWin32Cultures
All cultures that are installed in the Windows system. Note that not all cultures supported by the .NET Framework are installed in the Windows system.
NeutralCultures
Cultures that are associated with a language but are not specific to a country/region. The names of .NET Framework cultures consist of the lowercase two-letter code derived from ISO 639-1. For example: "en" (English) is a neutral culture.
ReplacementCultures
Custom cultures created by the user that replace cultures shipped with the .NET Framework.
SpecificCultures
Cultures that are specific to a country/region. The names of these cultures follow the RFC 1766 standard in the format "<languagecode2>-<country/regioncode2>", where <languagecode2> is a lowercase two-letter code derived from ISO 639-1 and <country/regioncode2> is an uppercase two-letter code derived from ISO 3166. For example, "en-US" (English - United States) is a specific culture.
UserCustomCulture
Custom cultures created by the user.
WindowsOnlyCultures
Cultures installed in the Windows system but not the .NET Framework.The WindowsOnlyCultures value is mutually exclusive with the FrameworkCultures value.

RegionInfo Class

One can gain more granular information about a culture by manipulating RegionInfo that exposes Country/Region of the culture. It can be created by passing in the Culture name or LCID numeric identifier.

Name
Description
CurrencyEnglishName
Gets the name, in English, of the currency used in the region.
CurrencyNativeName
Gets the name of the currency used in the region, formatted in the native language of the region.
CurrencySymbol
Gets the currency symbol associated with the country/region.
CurrentRegion (Static)
Gets the RegionInfo that represents the country/region used by the current thread.
DisplayName
Gets the full name of the country/region in the language of the localized version of .NET Framework.
EnglishName
Gets the full name of the country/region in English.
GeoId
Gets a unique identification number for a geographical region, country, city, or location.
IsMetric
Gets a value indicating whether the country/region uses the metric system for measurements.
ISOCurrencySymbol
Gets the three-character ISO 4217 currency symbol associated with the country/region.
Name
Gets the name or ISO 3166 two-letter country/region code for the current RegionInfo object.
NativeName
Gets the name of a region formatted in the native language of the region.
ThreeLetterISORegionName
Gets the three-letter code defined in ISO 3166 for the country/region.
ThreeLetterWindowsRegionName
Gets the three-letter code assigned by Windows to the country/region represented by this RegionInfo.
TwoLetterISORegionName
Gets the two-letter code defined in ISO 3166 for the country/region.

DateTimeFormatInfo and NumberFormatInfo Classes:
                DateTimeFormatInfo class provides comprehensive information to handle the differences between the cultures. For instance to display days of a weak in Venezuelan Spanish:

CultureInfo ci = new CultureInfor(“es-VE”);
String[] days = ci.DateTimeFormat.Days;
foreach ( string day in days)
                Console.Write(day + “ ”);

Same difference will be observed in months using ci.DateTimeFormat.MonthNames.

When dealing with numbers and currency, NumberFormatInfo can be used to control display as per culture.

Name
Description
CurrencyDecimalDigits
Indicates the number of decimal places to use in currency values.
CurrencyDecimalSeparator
Gets or sets the string to use as the decimal separator in currency values.
CurrencyGroupSeparator
Gets or sets the string that separates groups of digits to the left of the decimal in currency values.
CurrencyGroupSizes
Gets or sets the number of digits in each group to the left of the decimal in currency values.
CurrencyNegativePattern
Gets or sets the format pattern for negative currency values.
CurrencyPositivePattern
Gets or sets the format pattern for positive currency values.
CurrencySymbol
Gets or sets the string to use as the currency symbol.
CurrentInfo
Gets a read-only NumberFormatInfo that formats values based on the current culture.
DigitSubstitution
Gets or sets a value that specifies how the graphical user interface displays the shape of a digit.
InvariantInfo
Gets the default read-only NumberFormatInfo that is culture-independent (invariant).
IsReadOnly
Gets a value indicating whether the NumberFormatInfo is read-only.
NaNSymbol
Gets or sets the string that represents the IEEE NaN (not a number) value.
NativeDigits
Gets or sets a string array of native digits equivalent to the Western digits 0 through 9.
NegativeInfinitySymbol
Gets or sets the string that represents negative infinity.
NegativeSign
Gets or sets the string that denotes that the associated number is negative.
NumberDecimalDigits
Gets or sets the number of decimal places to use in numeric values.
NumberDecimalSeparator
Gets or sets the string to use as the decimal separator in numeric values.
NumberGroupSeparator
Gets or sets the string that separates groups of digits to the left of the decimal in numeric values.
NumberGroupSizes
Gets or sets the number of digits in each group to the left of the decimal in numeric values.
NumberNegativePattern
Gets or sets the format pattern for negative numeric values.
PercentDecimalDigits
Gets the number of decimal places to use in percent values.
PercentDecimalSeparator
Gets the string to use as the decimal separator in percent values.
PercentGroupSeparator
Gets the string that separates groups of digits to the left of the decimal in percent values.
PercentGroupSizes
Gets the number of digits in each group to the left of the decimal in percent values.
PercentNegativePattern
Gets or sets the format pattern for negative percent values.
PercentPositivePattern
Gets or sets the format pattern for positive percent values.
PercentSymbol
Gets or sets the string to use as the percent symbol.
PerMilleSymbol
Gets or sets the string to use as the per mille symbol.
PositiveInfinitySymbol
Gets or sets the string that represents positive infinity.
PositiveSign
Gets or sets the string that denotes that the associated number is positive.

Cultural Aware Comparison:
               CompareInfo and CompareOptions enumeration can be used to make comparison based on specific culture. Culture info has a property named CompareInfo that exposes the instance of the CompareInfo class. Following example illustrates the use of the Comparison based on French culture:





CompareOptions enumeration can be used in conjunction with CompareInfo to specialize the compare operation.
Class
Description
IgnoreCase
Indicates that the string comparison must ignore case.
IgnoreKanaType
Indicates that the string comparison must ignore the Kana type. Kana type refers to Japanese hiragana and katakana characters, which represent phonetic sounds in the Japanese language. Hiragana is used for native Japanese expressions and words, while katakana is used for words borrowed from other languages, such as "computer" or "Internet".
IgnoreNonSpace
Indicates that the string comparison must ignore nonspacing combining characters, such as diacritics. The Unicode Standard defines combining characters as characters that are combined with base characters to produce a new character. Nonspacing combining characters do not occupy a spacing position by themselves when rendered. For more information on nonspacing combining characters, see The Unicode Standard at http://www.unicode.org.
IgnoreSymbols
Indicates that the string comparison must ignore symbols, such as white-space characters, punctuation, currency symbols, the percent sign, mathematical symbols, the ampersand, and so on.
IgnoreWidth
Indicates that the string comparison must ignore the character width. For example, Japanese katakana characters can be written as full-width or half-width and, if this value is selected, the katakana characters written as full-width are considered equal to the same characters written in half-width.
None
Indicates the default option settings for string comparisons.
Ordinal
Indicates that the string comparison must be done using the Unicode values of each character, which is a fast comparison but is culture-insensitive. A string starting with "U+xxxx" comes before a string starting with "U+yyyy", if xxxx is less than yyyy. This flag cannot be combined with other flags and must be used alone.
OrdinalIgnoreCase
Indicates that the string comparison must ignore case, then perform an ordinal comparison. This is equivalent to converting the string to uppercase using the invariant culture and then performing an ordinal comparison on the result.
StringSort
Indicates that the string comparison must use the string sort algorithm, where the hyphen and the apostrophe, as well as other nonalphanumeric symbols, come before alphanumeric characters.



Comments

Popular posts from this blog

Concept of App Domain in .Net

Creating Application Domains: Application domain is just like process, provides separate memory space, and isolates from other code. But it’s quite light weight. It also provides the following advantages: 1-       Reliability : If a domain crashes, it can be unloaded. Hence doesn’t affect the other assemblies. 2-       Efficiency : Loading all assemblies in one domain can be cumbersome and can make the process heavy but Appdomains are efficient in this manner. Important properties of AppDomain: ApplicationIdentity , ApplicationTrust , BaseDirectory , CurrentDomain , DomainManager , DomainDirectory , Evidence , FriendlyName , ID , RelativeSearchPath , SetupInformation , ShadowCopyFiles . Important methods of AppDomain: ApplyPolicy , CreateCOMInstanceFrom , CreateDomain , CreateInstance (Assembly). To create an AppDomain: AppDomain adomain = AppDomain.CreateDomain(“D”); To execute an assembly:...

Asynchronous Execution in ASP.NET

Asynchronous Execution: Two ways either implement IHTTPAsyncHandler interface or in ASP.NET 2.0 set <%@ Page Async=”true” %>. The second option implements IHTTPAsyncHandler interface automatically for the page when parsed or compiled. AddOnPreRenderCompleteAsync ( new BeginEventHandler(BeginTask), new EndEventHandler(EndTask)); AddOnPreRenderCompleteAsync() shoud be called in Page_load. The BeginEventHandler and EndEventHandler are delegates defined as follows: IAsyncResult BeginEventHandler( object sender, EventArgs e, AsyncCallback cb, object state) void EndEventHandler( IAsyncResult ar) AsyncProcess starts and completes between PreRender and PreRenderComplete. Other way to perform Async Task is using AsyncPageTask structure. It also allows multiple tasks to execute simultaneously. void Page_Load (object sender, EventArgs e) { PageAsyncTask task = new PageAsyncTask( new BeginEventHandler(BeginTask), new EndEventH...