Localization
suggest changeIn .NET, building world-ready software involves two core disciplines:
- Globalization (G11N): Designing applications to support diverse languages, numeric systems, calendars, and cultural conventions.
- Localization (L10N): Translating and adapting an application's user interface and resources for specific regional cultures.
1. Understanding CultureInfo: CurrentCulture vs CurrentUICulture
The System.Globalization.CultureInfo class governs cultural formatting and localization:
CultureInfo.CurrentCulture: Controls culture-dependent data formatting, such as date/time patterns, decimal separators, currency symbols, and string sort orders.CultureInfo.CurrentUICulture: Determines the language used by the Resource Manager to look up localized UI strings and assets.CultureInfo.InvariantCulture: A fixed, culture-neutral representation (associated with the English language but invariant across regions). Always use this for data serialization, database storage, and network protocols.
using System;
using System.Globalization;
// Setting the culture for the current thread/task
CultureInfo.CurrentCulture = new CultureInfo("de-DE"); // Germany
CultureInfo.CurrentUICulture = new CultureInfo("de-DE");
decimal amount = 1299.50m;
DateTime date = new DateTime(2026, 10, 17);
// German formatting uses commas for decimals and points for thousands: "1.299,50 €"
Console.WriteLine(amount.ToString("C"));
// Date format: "17.10.2026"
Console.WriteLine(date.ToString("d"));
2. Formatting Across Cultures
You can pass an explicit IFormatProvider to formatting methods to bypass the thread's default culture:
using System;
using System.Globalization;
decimal price = 49.99m;
DateTime appointment = DateTime.UtcNow;
var cultures = new[]
{
new CultureInfo("en-US"), // United States
new CultureInfo("fr-FR"), // France
new CultureInfo("ja-JP"), // Japan
CultureInfo.InvariantCulture
};
foreach (var ci in cultures)
{
Console.WriteLine($"[{ci.Name}]");
Console.WriteLine($" Currency: {price.ToString("C", ci)}");
Console.WriteLine($" Date: {appointment.ToString("F", ci)}");
}
Invariant Formatting in String Interpolation
Using regular string interpolation ($"{amount}") formats data using CultureInfo.CurrentCulture. To guarantee machine-readable invariant formatting, use FormattableString.Invariant:
decimal latitude = 37.7749m;
decimal longitude = -122.4194m;
// Guarantees dot decimals ("lat=37.7749&lng=-122.4194") regardless of user regional settings
string query = FormattableString.Invariant($"lat={latitude}&lng={longitude}");
3. Localizing Strings with .resx Resource Files
The standard .NET mechanism for desktop, console, and library applications uses .resx resource files.
Resource File Hierarchy
Messages.resx: Default (fallback) strings (typically English).Messages.es.resx: Spanish translations.Messages.fr.resx: French translations.
Accessing Localized Strings via ResourceManager
using System;
using System.Globalization;
using System.Reflection;
using System.Resources;
class Program
{
private static readonly ResourceManager resMgr = new ResourceManager(
"MyApp.Resources.Messages",
Assembly.GetExecutingAssembly()
);
static void Main()
{
// 1. Retrieve string according to CurrentUICulture
string greeting = resMgr.GetString("WelcomeMessage") ?? "Welcome!";
Console.WriteLine(greeting);
// 2. Explicitly query a specific culture
string spanishGreeting = resMgr.GetString("WelcomeMessage", new CultureInfo("es-ES")) ?? "¡Bienvenido!";
Console.WriteLine(spanishGreeting);
}
}
4. Modern Web Localization in ASP.NET Core
ASP.NET Core provides the IStringLocalizer interface and request localization middleware.
1. Register Services and Middleware
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddLocalization(options => options.ResourcesPath = "Resources");
var app = builder.Build();
var supportedCultures = new[] { "en-US", "es", "fr", "de" };
var localizationOptions = new RequestLocalizationOptions()
.SetDefaultCulture("en-US")
.AddSupportedCultures(supportedCultures)
.AddSupportedUICultures(supportedCultures);
app.UseRequestLocalization(localizationOptions);
2. Injecting IStringLocalizer
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Localization;
[ApiController]
[Route("api/[controller]")]
public class NotificationController : ControllerBase
{
private readonly IStringLocalizer<NotificationController> _localizer;
public NotificationController(IStringLocalizer<NotificationController> localizer)
{
_localizer = localizer;
}
[HttpGet("welcome")]
public IActionResult GetWelcome([FromQuery] string username)
{
// Automatically selects translation matching request Accept-Language header or culture cookie
LocalizedString message = _localizer["WelcomeUser", username];
return Ok(new { message = message.Value });
}
}
5. Best Practices for Localization
- Never Hardcode Culture-Specific Characters: Never split or parse numbers using hardcoded
.or,characters; always specifyCultureInfo.InvariantCultureor the appropriateCultureInfo. - Composite Formatting over Concatenation: Translators often need to reorder words in sentences. Use parameterized placeholders rather than string concatenation:
// BAD: Word order is locked to English grammar string bad = "Hello " + user + ", you have " + count + " items."; // GOOD: Translators can reorder {0} and {1} in the resource file string good = string.Format(resMgr.GetString("UserItemCount"), user, count); - Distinguish Data from UI: Use
CurrentCulturefor rendering display strings in user interfaces, but always useInvariantCulturewhen writing JSON, XML, log files, or SQL queries.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents