Namespace System.Globalization C# Help

The Sys tern. Globali zation namespace holds all culture and region classes to support different date formats, different number formats, and even different calendars that are represented in classes such as GregorianCalendar, HebrewCalendar, JapaneseCalendar, and so on. By using these classes, you can display different representations depending on the user’s locale

This section looks at the following issues and considerations with using the System. Globalization narnespace:

¤  Unicode issues

¤  Cultures and regions

¤  An example showing all cultures and their characteristics

¤  Sorting

Unicode Issues

A Unicode character has 16bits, so there is room for 65,536characters. Is this enough for all languages currently used in information technology? In the case of the Chinese language, for example, more than 80,000characters are needed. However, Unicode has been designed to deal with this issue. With nicode you have to differentiate between base characters and combining characters. Youcan add mulbp combining characters to a base character to build up a single display character or a text elemen

Take, for example, the Icelandic character Ogonek. Ogonek can be combined by using the base character OxOO6F(Latin small letter 0) and the combining characters Ox0328(combining OgoneJ’l’o.:. Ox0304(combining Macron) as shown in Figure ~1-1.Combining characters are defined within from Ox0300to OX0345.For American and European markets, predefined characters exist to f dealing with special characters. The character Ogonek is also defined with the predefined cNlrJo::ZOx01ED

Figure 21-1

Figure 21-1

For Asian markets, where more than 80,000characters are necessary for Chinese alone, “characteor to the  characters do not exist. In Asian lariguages, you always have to deal with combining The problem is getting the right number of display characters or text elements, and getting characters instead of the combined characters. The namespace System. Globalizati – Stringlnfo, wh.i.ch you can use to deal with this issue.• The following table lists the static methods of the class Stringlnfo that help in dealing characters

Cultures and Regions

The world is divided into multiple cultures and regions, and applications have to be aware of these cultural and regional differences. A culture is a set of preferences based on a user’s language and cultural habits. RFC 1766(www. ietf . org /rfc/rfc1766. txt) defines culture names that are used worldwide depending on a language and a country or region. Some examples are en-AU, en-CA, en-GB, and en-US for the English language in Australia, Canada, the United Kingdom, and the United States, respectively

POSSiblythe most important class in the Sys tern. Globalization namespace is Cul turelnfo. Cul turelnfo represents a culture and defines calendars, formatting of numbers and dates, and sorting strings used with the culture.

The class Regionlnfo represents regional settings (such as the currency) and shows whether the region is using the metric system. Some regions can use multiple languages. One example is the region of Spain, which has Basque (eu-ES),Catalan (ca-ES),Spanish (es-ES),and Galician (gl-ES)cultures. Similar to one region having multiple languages, one language can be spoken in different regions; for example, Spanish is spoken in Mexico, Spain, Guatemala, Argentina, and Peru, to name only a few countries.

Later in this chapter, you see a sample application that demonstrates these characteristics of cultures
and regions

Specific, Neutral, and Invariant Cultures

With the use of cultures in the .NET Framework, you have to differentiate between three types: specific, neutral, and invariant cultures

A specific culture is associated with a real, existing culture defined with RFC 1766,as you saw in the preceding section. A specific culture cap)be mapped to a neutral culture. For example, de is the neutral culture of the specific cultures de-AT, de-DE, de-CH, and others. de is shorthand for the German language; AT,DE, and CH are shorthand for the countries Austria, Germany, and Switzerland, respectively.

When translating applications, it is typically not necessary to do translations for every region; not much difference exists between the German language in the countries Austria and Germany. Instead of using specific cultures, you can use a neutral culture for localizing applications

The invariant culture is independent of a real culture. When storing formatted numbers or dates in files, or sending them across a network to a server, using a culture that is independent of any user settings is the best option.

Figure 21-2 shows how the culture types relate to each other.

Figure 21-2

Figure 21-2

CurrentCulture and CurrentUICulture

When you set cultures, you need to differentiate between a culture for the user interface and a tun! for the number and date formats. Cultures are associated with a thread, and with these two culture rpes, two culture settings can be applied to a thread. The Thread class has the properties CurrentC1.!: =..=e and CurrentUICul ture. The property CurrentCul ture is for setting the culture that is used n form’!1ting and sort options, whereas the property CurrentUICul ture is used for the language of the user interface.

Users can change the default setting of the CurrentCul ture by using the Regional and Language options in the Windows Control Panel (see Figure 21-3). With this configuration, it is also possible to change the default number, the time, and the date format for the culture.

The CurrentUICul ture d6es not depend on this configuration. The CurrentUICul ture setting depends on the language of the operating system. There is one exception, though: If a multi-language user interface (MUI) is installed with Windows Vista or Windows XP,it is possible to change the language.pf the user interface with the regional configuration, and this influences the property CurrentUICulture.

These settings make a very good default, and in many cases, there is no need to change the default behavior. If the culture should be changed, you can easily do this by changing both cultures of the thread to, say, the Spanish culture, as shown in this code snippet

Now that you know about setting the culture, the following sections discuss number and date formatting, which are influenced by the CurrentCulture setting

Figure 21-3

Figure 21-3

Number Formatting

The number structures Int16, Int32, IntE4, and so on in the System namespace have an overloaded
ToString () method. This method can be used to create a different representation of the number depending on the locale. For the Int32 structure, ToString () is overloaded with these four versions:

public string ToString();
public string ToString(IFormatProvider);
public string ToString(string);
public string ToString(string, IFormatProvider);

ToStrillg () without arguments returns a string without format options. You can also pass a string and a class that implements IFormatProvider.

The string specifies the format of the representation. The format can be a standard numeric formatting string or a picture numeric formatting string. For standard numeric formatting, strings are predefined, where Cspecifies the currency notation, Dcreates a decimal output, E creates scientific output, F creates fixed-point output, Gcreates general output, Ncreates number output, and Xcreates hexadecimal output. With a picture numeric fonnat string, it is possible to specify the number of digits, section and group separators, percent notation, and so on. The picture numeric format string 111111 , II * * means two three-digit blocks separated by a group separator. .

The IFormatProvider interface is implemented by the Number FormatInfo, Date TimeFormatInfo, and CultureInfo classes. This interface defines a single method, GetFormat (), that returns a format object.

Number Forrnat lnfo can be used to define custom formats for numbers. With the default constructor of Number Forrnat lnfo, a culture-independent or invariant object is created. Using the properties of Number Format lnfo, it is possible to change all the formatting options, such as a positive sign, a percent symbol, a number group separator, a currency symbol, and a lot more. A read-only culture-independentNumberForrnatlnfo object is returned from the static property Invariantlnfo. ANumberForrnatlnfo object in which the format values are based on the CuI turelnfo of the current thread is returned from the static property Currentlnfo.

To create the next example, you can start with a simple console project. In this code, the first example shows a number displayed in the format of the culture of the thread (here: English-US, the setting of the operating system). The second example uses the ToString () method with the I Format Provider argument. CuIture Info implements I Format Provider, so create a Culture lnfo object using the French culture. The third example changes the culture of the thread. The culture is changed to German using the property Current Culture of the Thread instance:

The output is shown here. Youcan compare the outputs with the previously’ listed differences for U.S.
English, French, and German.

1,234,567,890.00
1 234 567 890,00
1.234.567.890,00

Date Formatting

The same support for numbers is available for dates. The OateTime structure has some methods for date-to-string conversions. The public instance methods ToLongOateString () , ToLongTimeString ( ), ToShortOateString (), and ToShortTimeString () create string representations using the current culture. You can use the ToString () method to assign a different culture:

public string ToString();
public string ToString(IFormatProvider);
public string ToString(string);
public string ToString(string, IFormatProvider);
With the string argument of the ToString () method, you can specify a predefined format character or a custom format string for converting the date to a string. The class DateTimeForrnatlnfo specifies the possible values. With DateTimeForrnatlnfo, the case of the format strings has a different meaning. D defines a long date format, d a short date format. Other examples of possible formats are ddd for the abbreviated day of the week, dddd for the full day of the week, yyyy for the year, Tfor a long time, and t for a short time format. With the IFormatProvider argument, you can specify the culture. Using an overloaded method without the IFormatProvider argument implies that the culture of the current

thread is used: DateTime d a new DateTime(2008, 02, 14);
II current culture Console.WriteLine(d.ToLongDateString(»;
II use IFormatProvider Console.WriteLine(d.ToString(‘D’, new Culturelnfo(‘fr-FR’»);
II use culture of thread Culturelnfo ci z Thread. CUrrentThread. CurrentCUlture;
Console.WriteLine(‘{O): (I)’, ci.ToString(), d.ToString(‘D’»

;
..•
ci z new CUlturelnfo(‘es-ES’); Thread.CurrentThread.CUrrentCulture a ci; Console.WriteLine(‘{O): (I)’, ci.ToString(), d.ToString(‘D’»; The output of this example program shows ToLongDateStrong () with the current culture of the thread, a French version where a CuIturelnfo instance is passed to the ToString () method, and a Spanish version where the CurrentCulture property of the thread is changed to es-ES: Thursday, February 14, 2~08 jeudi 14 fevrier 2008 .  en-US: Thursday, February 14, 2008 e.-ES: jeuvel, 14 de febrero de 2008

Cultures In ActIon

To see all cultures in action, you can use a sample WPF appliration that lists all cultures and demonstrates different characteristics of culture properties. Figure 21-4 shows the user interface of the application in the Visual Studio 2008 W~F Designer. During initialization of the application, all available cultures are added to the tree view control that is placed on the left side of the application. This initialization happens in the method Add

Culture a To Tree () that is called in the constructor of the Windowclass CuIture DemoWindow

Figure 21-4

Figure 21-4

In the method AddCul turesToTree (), you get all cultures from the static method Cul turelnfo. GetCul tures (). Passing Cul tureTypes. AllCul tures to this method returns an unsorted array of all available cultures. The array is sorted using a Lambda expression that is passed to the Comparison delegate of the second argument of the Array. Sort () method. Next, in the foreach Io?’p, every single culture is added to the tree view. A TreeViewItem object is created for every single culture because the WPF Treeview class uses TreeViewItem objects for display. The Tag property of the TreeViewItem object is set to the Culturelnfo object, so that you can access the

Cul turelnfo object at a later time from within the tree.

Where the Tree View Item is added inside the tree depends on the culture type. If the culture does not have a parent culture, it is added to the root nodes of the tree. To find parent cultures, all cultures are remembered inside a dictionary. Recall Chapter 10, “Collections,” for more information about dictionaries and Chapter 7, “Delegates and Events” for Lambda expressions.

When the user selects a node inside the tree, the handler of the SelectedltemChanged event of the Treeview will be called. Here the handler is implemented in the method TreeCul tures_ SelectedItemChanged ( ) . Within this method, all fields are cleared by calling the method ClearTextFields () before you get the CuI turelnfo object from the tree by selecting the Tag property of the TreeViewItem. Then some text fields are set using the properties Name, NativeName, and EnglishName of the Culturelnfo object. U the CuI turelnfo is a neutral culture that can be queried with the IsNeutralCul ture property, the corresponding check box will be set:

Then you get the calendar information about the culture. The Calendar property of the Culturelnfo class returns the default Calendar object for the specific culture. Because the Calendar class doesn’t have a property to tell its name, you use the ToString () method of the base class to get the name of the class, and removethe namespace of this string to be displayed in the text field textCalendar.

Because a single culture might support multiple calendars, the OptionalCalendars property returns an array of additional supported Calendar objects. These optional calendars are displayed in the list box listCalendars. The GregorianCalendar class that derives from Calendar has an additional property called CalendarType that lists the type of the Gregorian calendar. This type can be a value of the enumeration GregorianCalendarTypes: Arabic, MiddleEastFrench, Transli teratedFrench, USEnglish, or Localized depending on the culture. With Gregorian calendars, the type is also displayed in the list box:

Next, you check whether the culture is a specific culture (not a neutral culture) by using !ci. IsNeutralCul ture in an if statement. The method ShowSamples ()displays number and date samples. This method is implemented in the next code section. The method ShowRegionlnforrnation ()is used to display some information about the region. With the invariant culture, you can display only number and date samples, but no region information. The invariant culture is not related to any real language, and therefore it is not associated with a region:

To show some localized sample numbers and dates, the selected object of type Culturelnfo is passed with the IFormatProvider argument of the ToString ()method:

To display the information associated with a Regionlnfo object,in the method ShowRegionlnformation () a Regionlnfo objectisconstructed passing the selectedculture identifier.Then-you access the properties OisplayName, CurrencySymbol, ISOCurrencySymbol, and IaMetric propertiesto display thisinformation:

When you startthe application,you can s,· allavailableculturesin the treeview, and selectinga culture liststhe cult.uralcharacteristicsa,s shown in Figure 21-5.

Fllur.21·5

Figure.21·5

Sorting

Sorting strings is dependent on the culture. Some cultures have rlifferent sorting orders. One example is Finnish, where the characters V and Ware treated the same. The algorithms that compare strings for sorting by default use a culture-sensitive sort, in which the sort is dependent on the culture. To demonstrate this behavior with a Finnish sort, the following code creates a small sample console application where some U.S. states are stored unsorted inside an array. You are going to use classes from the namespaces System. Collections. Generic, Gystem. Threading, and System. Globalization, .•u these namespaces must be declared. The method DisplayNames () shown here is used to display all elements of an array or of a collection on the console:

In the Main () method, after creating the array with some of the U.S. states, the thread property CurrentCul ture is set to the Finnish culture, so that the following Array. Sort () uses the Finnish sort order., Calling the method Di splayNames () displays all the states on the console

After the first display of some U.s. states in the Finnish sort order, the array is sorted once again. If you want to have a so!’! that is independent of the users’ culture, which would be useful when the sorted arr.1.yis sent to a server or stored somewhere, you can use the invariant culture. You can do this by passing a second argument to Array. Sort ( ) . The Sort () method expects an object implementing IComparer with the second argument. The Comparer class from the System. Collections namespace implements IComparer. Comparer. Defaul tlnvariant returns a Comparer object that uses the invariant culture for comparing the array values for a culture-independent sort:

The program output shows different sorts with the Finnish and the culture-independent cultures: Virginia goes before Washington when using the invariant sort order and vice versa using Finnish.

Sorted using the Finnish culture Alabama – Alaska – Arizona – Hawaii – Kansas – Kentucky – Louisiana – Missouri – Texas – Utah – Washington – Virginia – Wisconsin – Wyoming – Sorted using the invariant culture Alabama – Alaska – Arizona – Hawaii – Kansas – Kentucky – Louisiana – Missouri – Texas – Utah – Virginia – Washington – Wyoming.

In addition to a locale-dependent formatting and measurement system, text and pictures may differ depending on the culture. This is where resources come into play.

Posted on October 31, 2015 in Localization

Share the Story

Back to Top