Skip to content

Globalization & localization

Targets net11.0 csharp-15Last reviewed 2026-11-18 freshSources andrew-lock avalonia-blog jon-skeet khalid meziantou ms-learn steve-gordon

Localize with .resx resources behind IStringLocalizer<T>, select the culture with the request localization middleware, and use ICU (International Components for Unicode) for culture data on every platform. The bugs come from three defaults:

  • Format, parse, and compare calls use the current culture, even for text that a machine reads.
  • A project template turns on invariant mode before anyone decides whether the app should use it.
  • Size-optimised container images leave out the ICU and time zone data the runtime needs.

Opinions

Split every format, parse, and compare call by audience

Use the current culture for text people read. For text machines read, pass CultureInfo.InvariantCulture explicitly, and compare with StringComparison.Ordinal. This rule prevents most globalization bugs, and the machine-facing half is the one people skip. Nothing fails until the service runs under de-DE and 1.5 round-trips as 15. (Microsoft Learn: Best practices for comparing strings, Microsoft Learn: Double.Parse)

Audience Formatting and parsing Comparison
A person reading a screen CurrentCulture (the default) CurrentCulture, for sorting a displayed list
A machine: JSON, logs, URLs, file names, config, DB round-trips CultureInfo.InvariantCulture, explicitly StringComparison.Ordinal

Never use StringComparison.InvariantCulture or InvariantCultureIgnoreCase. Only the culture data is invariant. The collation follows the host's ICU or NLS version, so the same comparison can return different results on two machines. Use InvariantCulture for formatting and parsing, never for comparison. (Meziantou: StringComparison.InvariantCulture is not always invariant, Microsoft Learn: Globalization and ICU)

// Wrong: the host's collation decides, and hosts disagree
if (string.Equals(header, "application/json", StringComparison.InvariantCultureIgnoreCase))

// Right: a protocol token is machine-facing
if (string.Equals(header, "application/json", StringComparison.OrdinalIgnoreCase))

The .NET SDK's code analysis rules report the calls to fix:

Rule Reports
CA1304, CA1305 Formatting without a culture
CA1309 InvariantCulture comparison in Equals and Compare
CA1310, CA1311 IndexOf and casing without a culture

All five warn at the latest-recommended level that templates/Directory.Build.props sets. CA1307 needs an explicit severity, which templates/.editorconfig sets:

dotnet_diagnostic.CA1307.severity = warning

With TreatWarningsAsErrors on, a missing StringComparison fails the build. Meziantou.Analyzer, described in csharp.md, covers the same cases.

Ban the two invariant comparisons with Microsoft.CodeAnalysis.BannedApiAnalyzers, because CA1309 checks only Equals and Compare. On SDK 11.0.100, neither CA1309 nor Meziantou.Analyzer 3.0.340 reports StringComparison.InvariantCulture in StartsWith, EndsWith, IndexOf, or Contains. templates/BannedSymbols.txt bans both enum fields, so RS0030 reports every use in C# and Visual Basic, whatever the call. templates/Directory.Build.props adds the package and passes the file to every project. Keep the file beside Directory.Build.props, at the repository root. Roslyn analyzers don't run in an F# build, so an F# project that uses either field still builds. (Meziantou: StringComparison.InvariantCulture is not always invariant, Roslyn: BannedApiAnalyzers, Microsoft Learn: CA1309)

// CA1309 reports this one
var isJson = string.Equals(header, "application/json", StringComparison.InvariantCultureIgnoreCase);

// CA1309 and Meziantou.Analyzer stay silent, and only RS0030 reports it
var isApplication = header.StartsWith("application/", StringComparison.InvariantCultureIgnoreCase);

Treat InvariantGlobalization as an explicit decision, never an inherited template line

Make invariant mode its own decision, and comment the property where you set it. <InvariantGlobalization>true</InvariantGlobalization> makes the runtime skip ICU and use built-in invariant data. That saves size and startup time for a service with no localized output. It's a mistake when nobody chose it, and it usually arrives with an unrelated decision.

On SDK 10.0.400, dotnet new webapi doesn't set it, but dotnet new webapiaot does, next to <PublishAot>true</PublishAot>. So the property comes in when someone adopts Native AOT, as described in runtime-performance.md. It then changes what every ToString and Compare call in the app does.

Turning it on costs you:

  • Every culture except the invariant one. Constructing another CultureInfo throws, unless you also set PredefinedCulturesOnly=false.
  • TimeZoneInfo.TryConvertIanaIdToWindowsId and TryConvertWindowsIdToIanaId, which need ICU.
  • Linguistic casing and collation. Invariant mode isn't a substitute for Ordinal: the audience split still applies.

(Microsoft Learn: Globalization config settings, Microsoft Learn: Globalization and ICU)

Pin ICU only when a sort order is part of your contract

Use the system ICU unless you have a stated reason not to. .NET has used ICU on every platform since .NET 5, including Windows, which ships icu.dll. The alternatives, from most to least often right:

  • System.Globalization.AppLocalIcu, with a Microsoft.ICU.ICU4C.Runtime package reference, ships a pinned ICU with the app. Collation and CLDR data are then identical in every deployment. Use it when a sort order is part of your contract.
  • DOTNET_ICU_VERSION_OVERRIDE pins a system ICU version on Linux. Before .NET 10, it was CLR_ICU_VERSION_OVERRIDE. It works only on Microsoft-built .NET, not distribution builds. (Microsoft Learn: Breaking changes in .NET 10)
  • System.Globalization.UseNls reverts to Windows NLS. Use it only for bug compatibility with a legacy app: you lose the IANA and Windows time zone ID conversions. Since .NET 9, the environment variable overrides the runtimeconfig.json value. Before .NET 9, it was the other way round.

(Microsoft Learn: Globalization and ICU, Microsoft Learn: Globalization config settings)

Call AddLocalization with a ResourcesPath, and select the culture with UseRequestLocalization early in the pipeline.

builder.Services.AddLocalization(options => options.ResourcesPath = "Resources");

string[] supportedCultures = ["en-GB", "fr", "de"];
app.UseRequestLocalization(new RequestLocalizationOptions()
    .SetDefaultCulture(supportedCultures[0])
    .AddSupportedCultures(supportedCultures)
    .AddSupportedUICultures(supportedCultures));

In production, four details decide whether it works:

  • SupportedCultures and SupportedUICultures are independent. CurrentCulture controls number, date, and currency formatting, and sorting. CurrentUICulture controls which .resx file ResourceManager resolves. English text with German number formatting is a valid configuration. (Microsoft Learn: Globalization and localization in ASP.NET Core)
  • Providers run in order: query string, cookie, then Accept-Language. The first match wins. On every request, "the first provider that can successfully determine the request culture is used". (Microsoft Learn: Select the language/culture for each request in a localized ASP.NET Core app) Use the cookie in production, and the query string for debugging. Lock calls the cookie "the least intrusive" of the three, because it "does not require the user to set the Accept-Language header in their browser". Give users a way to set their culture, and store it in the cookie. (Lock: Adding Localisation to an ASP.NET Core application)
  • Order the middleware. Call UseRequestLocalization before anything that reads the culture. If you use RouteDataRequestCultureProvider, call it after routing. (Microsoft Learn: Globalization and localization in ASP.NET Core)
  • Fallback works per resource and ends at the default file: Welcome.fr-CA.resx, then Welcome.fr.resx, then Welcome.resx. To show the key for a missing translation instead of the default language's text, don't ship a default .resx file.

If RootNamespace and AssemblyName differ, resource lookup fails completely. A project directory named my-project-name causes this. Fix it with [assembly: RootNamespace] and [assembly: ResourceLocation], not by renaming resources. (Microsoft Learn: Globalization and localization in ASP.NET Core)

Name resource keys with a constants class, not magic strings

Pass keys to IStringLocalizer from a static class ResourceKeys of const string fields. IStringLocalizer accepts the default-language text as the key, as in _localizer["About Title"]. That skips the up-front .resx work but scatters magic strings through the code. A constants class keeps each key in one place, and works in attributes such as [Display(Name = ResourceKeys.AboutTitle)]. (Lock: Localising the DisplayAttribute and avoiding magic strings)

A strongly typed resource class doesn't replace the constants class. Its members are static properties that return the localized text through a ResourceManager, not const keys, so they can't go to IStringLocalizer or into an attribute argument. nameof on a member is a constant, but it gives the member's name, not the key. The two differ whenever the key isn't a C# identifier: the generator names the member for Errors.Required as Errors_Required, and no resource has that name.

Where code reads resources without IStringLocalizer, as Avalonia's {x:Static} does below, generate the class in the build:

  • MSBuild's own generator "runs on every platform and every IDE". Set <Generator>MSBuild:Compile</Generator> and the StronglyTyped metadata on the EmbeddedResource, with StronglyTypedFileName under $(IntermediateOutputPath), so the class goes to obj/ and stays out of source control. Add <PublicClass>true</PublicClass> when XAML reads the class, because {x:Static} can't reach an internal one. (Avalonia Docs: Localizing using ResX)
  • The designer needs Visual Studio and a checked-in .Designer.cs file. (Abuhakmeh: Getting Started With .NET Localization)
  • <GenerateSource>true</GenerateSource> on an EmbeddedResource builds cleanly and generates nothing.
  • Microsoft.CodeAnalysis.ResxSourceGenerator has only prerelease versions. Revisit this when a stable version ships. (NuGet: Microsoft.CodeAnalysis.ResxSourceGenerator)

Client-side: ship the globalization data the app can reach

  • Blazor WebAssembly loads only the app's own culture data by default. If users can switch culture at run time, set <BlazorWebAssemblyLoadAllGlobalizationData>true</BlazorWebAssemblyLoadAllGlobalizationData>.

    • Time zone data is trimmed separately, with <InvariantTimezone>true</InvariantTimezone>. Delete <BlazorEnableTimeZoneSupport>, which it replaces.
    • Since .NET 10, standalone WebAssembly apps also load data for CultureInfo.DefaultThreadCurrentUICulture. .NET 9 and earlier used only DefaultThreadCurrentCulture.

    (Microsoft Learn: Blazor globalization and localization)

  • In a Blazor Web App, leave UseCultureFromServer on. From .NET 11, client-side prerendering persists the server's CurrentCulture and CurrentUICulture, "and applies them on the client before satellite assemblies load". Set WebAssemblyComponentsOptions.UseCultureFromServer to false only when the client has to choose its culture independently of the server. (Microsoft Learn: Blazor globalization and localization)

  • .NET MAUI has no localization abstraction. It uses .resx files per culture and CultureInfo.DefaultThreadCurrentUICulture, with nothing like RequestLocalization. To switch culture at run time, re-resolve bindings yourself. (Microsoft Learn: .NET MAUI localization)

  • Avalonia reads .resx in XAML with {x:Static} against a generated resources class. {x:Static} reads the string once. To switch language without a restart, "Reload the view or window", so the references are evaluated again. The cited source is Avalonia's own documentation, so trust it for how this works, not for whether to use it. The caveat in ui-frameworks.md applies. (Avalonia Docs: Localizing using ResX)

Containers: chiseled and Alpine images drop this data

If the app formats dates, sorts text, or resolves a time zone, use the -extra image tag. project-structure.md recommends resolute-chiseled or alpine images for size. Those size-optimised images (Alpine, Ubuntu chiseled, and the Azure Linux images that the page lists as "Mariner distroless") "don't include globalization dependencies such as ICU or tzdata … only work with apps that are configured for globalization invariant mode". Each has an -extra variant, such as 11.0-alpine-extra or 11.0-resolute-chiseled-extra, that adds back ICU, tzdata, and stdc++. (Microsoft Learn: .NET container images, dotnet/dotnet-docker: .NET Image Variants)

The two missing pieces fail differently:

Localization makes dates look right, not be right

Store instants as UTC, store the user's IANA time zone ID instead of a fixed offset, and convert at the edge. For storage and type guidance, including when a future local event should not become UTC, see datetime.md. "Sometimes, a local date/time occurs twice", and correct formatting can't fix a value that was ambiguous before it was formatted. Noda Time separates LocalDateTime from ZonedDateTime for this reason. (Skeet: More fun with DateTime)

TimeZoneInfo.TryConvertIanaIdToWindowsId and TryConvertWindowsIdToIanaId work only outside invariant and NLS modes. So decide on this storage choice, invariant mode, and ICU together.