Skip to content
Tutorials Center
My learning

Topics

Lesson 128 of 182 Β· Standard Library

Localization and Globalization

Learn globalization and localization in C# and ASP.NET Core - cultures, number and date formats, resource files with fallback, plural rules and Accept-Language negotiation - with runnable demos.

Software that is used in more than one country meets a surprising number of small differences. Germans write 1.234,56 where Americans write 1,234.56. The same date is 3/9/2025 in one country and 9.3.2025 in another. Some languages have two plural forms, others have four, and some have none. Making a program cope with all of this has two halves with two awkward names. Globalization is making the code culture-aware: formatting, parsing, sorting and comparing text according to the rules of a culture. Localization is translating the user interface: replacing the English texts with texts for each language you support.

.NET has a mature toolbox for both: CultureInfo, format providers, .resx resource files, ResourceManager, and in ASP.NET Core the IStringLocalizer interface plus request-localization middleware. This lesson explains how the pieces fit, and builds a small resource lookup yourself so you see the algorithm instead of just the API. It builds on string formatting, dates and times and, for the web example, middleware.

Our in-browser server runs .NET in invariant globalization mode: only the invariant culture exists, and new CultureInfo("de-DE") throws CultureNotFoundException. On a normal machine the real cultures are there. So the runnable examples here build the culture data by hand (a NumberFormatInfo is just an object with settings), and the lines that need real operating-system cultures are shown read-only, labeled as such.

Cultures: language plus region

A culture is a name such as en, en-US, fr-CA or de-DE: a language, optionally followed by a region. A culture without a region (fr) is neutral; one with a region (fr-CA) is specific and carries concrete formatting data such as the currency symbol. The special invariant culture (CultureInfo.InvariantCulture, the empty name) is not tied to any country; it is a stable, English-flavored baseline meant for data that machines read.

Every thread has two current cultures, and they do different jobs:

Property Controls Typical use
CultureInfo.CurrentCulture formatting and parsing: numbers, dates, currency, sorting ToString(), double.Parse, string.Compare
CultureInfo.CurrentUICulture which translation resources are loaded ResourceManager, IStringLocalizer

They can differ. A user may want English menus (UI culture en) but dates and numbers the way their country writes them (culture de-DE). In a web server, the "current" culture is not the server's: it must be set per request, from what the browser asks for (see the last section), because one server handles users from everywhere.

Because CurrentCulture is picked up by default, the same code gives different text on different machines. That is wanted for text shown to people and a bug for text read by programs (files, URLs, logs, JSON). The rule from string formatting bears repeating: user interface text uses the user's culture; machine-readable text uses CultureInfo.InvariantCulture.

Culture-aware formatting

A culture's formatting rules live in two objects: NumberFormatInfo (decimal separator, group separator, currency symbol and position, negative sign) and DateTimeFormatInfo (month and day names, patterns, first day of the week). Methods such as ToString(format, provider) accept any IFormatProvider, and a NumberFormatInfo is one. On a normal machine you would write CultureInfo.GetCultureInfo("fr-FR"). Here we configure the objects directly, which shows exactly what a culture is:

C# Formatting numbers and dates for a culture

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The same number printed as 1,234,567.89 and 1.234.567,89: only the provider changed. The parsing lines make the mirror-image point. "1.234,50" is a valid price in German and not a valid number to the invariant culture, so a program that formats with one culture and parses with another corrupts data silently or fails. On a real machine, the same effects come from named cultures (read-only; the exact space characters are language-specific):

C#
// Read-only: needs real ICU/NLS culture data, not available in the invariant-mode runner
var de = CultureInfo.GetCultureInfo("de-DE");
var fr = CultureInfo.GetCultureInfo("fr-FR");
1234567.891.ToString("N2", de);                 // 1.234.567,89
1234567.891.ToString("C", de);                  // 1.234.567,89 €
new DateTime(2025, 3, 9).ToString("D", fr);     // dimanche 9 mars 2025
CultureInfo.CurrentCulture = de;                // all later default formatting now uses German rules

Three more places where culture changes behavior, and the safe defaults:

  • Comparing and sorting. string.Compare(a, b) and ToUpper() use the current culture; in Turkish, "i".ToUpper() is "Δ°" and the famous "Turkish I problem" breaks code that compares file names or keywords this way. For identifiers, keys and paths use StringComparison.Ordinal or OrdinalIgnoreCase; for text shown to people in sorted order use culture comparison on purpose. See strings for the full list.
  • Casing and normalization. ToUpperInvariant() and ToLowerInvariant() give the same answer everywhere.
  • Calendars and time zones. A culture may use a non-Gregorian default calendar, and "local time" depends on the time zone, not the culture. Store timestamps in UTC (DateTimeOffset) and convert for display only.

Resource files and fallback

Hard-coded English strings in code cannot be translated. The .NET way is resources: keys mapped to texts, one set per culture. In a project you create Strings.resx (the default, or neutral, language) and Strings.fr.resx, Strings.fr-CA.resx, and so on. The build compiles each into a binary .resources blob, and non-default ones into small satellite assemblies in per-culture folders. At runtime ResourceManager.GetString("Welcome") looks the key up for CurrentUICulture.

The important rule is the fallback chain. If the user's UI culture is fr-CA, the lookup tries fr-CA, then its parent fr, then the default resources. A translation file therefore only needs the strings that differ: fr-CA can hold just the three words Canadian French spells differently, and everything else falls through to fr.

flowchart LR
    A["Lookup key 'Save'<br/>UI culture fr-CA"] --> B{"fr-CA<br/>has key?"}
    B -- yes --> R["Use it"]
    B -- no --> C{"fr<br/>has key?"}
    C -- yes --> R
    C -- no --> D{"Default<br/>(neutral) has key?"}
    D -- yes --> R
    D -- no --> N["Return the key itself<br/>and mark as not found"]

Resource lookup walks from the most specific culture to the default; only a missing key everywhere counts as "not found".

Rather than hide this behind ResourceManager, the next program implements it. It writes real binary .resources data into memory with ResourceWriter (this is what the build does with .resx files), reads it back with ResourceSet, and implements ASP.NET Core's IStringLocalizer interface so the code you write against it is exactly what you would write in a real project. Missing keys are reported through LocalizedString.ResourceNotFound, which is how you spot untranslated text in production logs.

C# A resource catalog with culture fallback

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Read the table of results as a fallback demonstration. fr-CA got its own "Sauvegarder" but inherited "Bienvenue" and "Annuler" from fr. fr-FR has no file of its own, so everything came from fr. de-AT (Austrian German) fell back to de for the texts it has and to the default for "Cancel", which German does not define yet. Japanese has nothing, so the whole screen is in the default language, which is the correct failure mode: always ship a complete default language so users never see a blank.

In an ASP.NET Core project the same interface comes from dependency injection (builder.Services.AddLocalization()), and ResourceManager does the work behind the scenes:

C#
// Read-only: a real project with Resources/Strings.resx and Resources/Strings.fr.resx
public class CheckoutController(IStringLocalizer<CheckoutController> localizer) : Controller
{
    public IActionResult Index() => Content(localizer["Welcome", User.Identity!.Name!]);
}

Use descriptive keys (Cart.Empty, Checkout.PayNow) or the English sentence itself as the key, and be consistent. Never build sentences by gluing translated fragments together ("You have " + n + " " + localizer["items"]): word order differs between languages. Translate the whole sentence with placeholders, as the in the example does, and give translators context in comments.

Plurals and other grammar traps

English has two plural forms (1 item, 2 items), so the beginner's n == 1 ? "item" : "items" seems enough. It is not. French treats 0 and 1 as singular. Russian and Polish distinguish one, few and many depending on the last digits. Arabic has six forms. Japanese has one. Good localization asks a plural rule which category a number falls in, and the translation file supplies one sentence per category. Standards bodies publish these rules in the CLDR; libraries such as ICU MessageFormat implement them. The built-in .NET resources do not, so most teams either add a message-format library or implement the few rules their languages need, which is easy to do:

flowchart TD
    N["number n"] --> L{"language"}
    L -- en --> E["n = 1: one<br/>otherwise: other"]
    L -- fr --> F["n = 0 or 1: one<br/>otherwise: other"]
    L -- ru --> R["last digit 1 (not 11): one<br/>last digit 2-4 (not 12-14): few<br/>otherwise: many"]

A plural rule maps a number to a category; each language's translation provides one text per category.

C# Plural rules per language

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Look at 0, 1 and 21: English and French disagree about zero, and Russian uses the one form for 21 but the many form for 11. This is why "just add an s" never survives contact with a real translation. The same care applies to gender and case (a translated phrase may need different endings depending on a name), text length (German and Finnish are often 30% longer than English, so layouts must not be pixel-perfect), right-to-left scripts (Arabic and Hebrew mirror the whole layout), and names and addresses (do not assume a first/last name split or a postal-code format).

Choosing the culture per request in ASP.NET Core

On a server there is one process and many users, so each request needs its own culture. ASP.NET Core provides UseRequestLocalization middleware, which looks at the ?culture= query string, a cookie, and the browser's Accept-Language header, in that order, and sets CurrentCulture and CurrentUICulture for the rest of the request. Real setup (read-only here because it creates named cultures):

C#
// Read-only: needs real cultures
var supported = new[] { "en", "fr", "de" };
app.UseRequestLocalization(new RequestLocalizationOptions()
    .SetDefaultCulture("en")
    .AddSupportedCultures(supported)
    .AddSupportedUICultures(supported));

The browser's Accept-Language header is a ranked list such as fr-CA,fr;q=0.9,en;q=0.5, where q is the preference weight (default 1). Negotiation means: go through the user's languages from best to worst and pick the first one you support, trying the parent when the exact culture is missing. You can read the header already parsed with Request.GetTypedHeaders().AcceptLanguage. The next program does the negotiation by hand and plugs it into the catalog from before, so you see one API serving three different users:

C# Accept-Language negotiation in a minimal API

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The first user prefers Canadian French, which is not supported exactly, so the neutral fr is used. The second asks for Japanese first, which is not supported, and falls through to German (weight 0.8). The Spanish speaker has no match at all and gets the default. Note the weights are compared, not the order of appearance: the fourth user wrote English first but weighted it lower. Two response headers matter for correctness: Content-Language tells clients what they got, and Vary: Accept-Language stops a shared cache or CDN from serving the French page to everyone (see deployment for the caching side).

A last design note: Accept-Language is a good first guess, but let users override it with a language switcher that stores the choice in a cookie or in their profile, and put the language in the URL (/fr/products) for pages you want search engines to index separately.

Globalization checklist

  • Store and exchange data in invariant formats: UTC timestamps, ISO 8601 dates, numbers formatted with CultureInfo.InvariantCulture, UTF-8 text.
  • Show data in the user's formats: let CurrentCulture format numbers and dates; never hard-code MM/dd/yyyy.
  • Keep all user-visible strings in resources; no sentence building by concatenation; give translators placeholders and context.
  • Use ordinal comparisons for identifiers, protocols and file names, culture comparisons for text sorted for humans.
  • Test with a pseudo-language (for example, wrap every string as [!! ÜnΓ―cΓΆdΓ© text !!]) to find untranslated and truncated text early, and with long German text and a right-to-left language for layout.
  • Never assume the server's culture is the user's culture.

Check your understanding

Quick check Β· 5 questions

of 5 answered You scored / 5 Β· perfect!

  1. 1. What is the difference between CurrentCulture and CurrentUICulture?

    Formatting and sorting follow CurrentCulture; ResourceManager and IStringLocalizer follow CurrentUICulture. A user can have English menus and German number formats.
  2. 2. A resource lookup for the UI culture fr-CA cannot find the key 'Cancel' in fr-CA. What happens next?

    The fallback chain is specific culture, then parent culture, then the neutral/default resources. That is why a regional file only needs the texts that differ.
  3. 3. Which text should be written and read with CultureInfo.InvariantCulture?

    Machine-readable data must not change with the machine's settings. Text shown to people should use their culture.
  4. 4. Why is 'n == 1 ? "item" : "items"' not a good general plural strategy?

    French treats 0 as singular, Russian has one/few/many with rules about the last digits, Arabic has six forms. Use per-language plural rules and one translation per category.
  5. 5. An API returns different text depending on Accept-Language. Which header keeps a shared cache from serving the French version to everybody?

    Vary tells caches that the response depends on that request header, so they store one copy per distinct value. Content-Language only describes the response.

Summary

  • Globalization is culture-aware code; localization is translating the UI. CurrentCulture drives formatting and parsing, CurrentUICulture drives which translations load.
  • Use the user's culture for display and InvariantCulture for stored or exchanged data; use ordinal comparisons for identifiers.
  • Resources map keys to texts per culture, with a fallback from fr-CA to fr to the default; always ship a complete default language.
  • Translate whole sentences with placeholders, and use per-language plural rules instead of n == 1.
  • In ASP.NET Core, set the culture per request from the query string, a cookie or Accept-Language, and send Content-Language and Vary: Accept-Language.
  • Test with pseudo-localization, long text and right-to-left layouts.

Next: Dependency Injection