.NET 4.5 Baby Steps, Part 8: AppDomain wide culture settings

Submitted by Robert MacLean on Wed, 05/09/2012 - 13:17
Other posts in this series can be found on the Series Index Page

Introduction

Culture settings in .NET are a very important but often ignored part of development, they define how numbers, dates and currencies are displayed and parsed and you application can easily break when it is exposed to a new culture.

In .NET 4, we could do three things:

  • Ignore it
  • Set it manually everywhere
  • If we were using threads, we could set the thread culture.

So lets see how that works:

// uses the system settings
Console.WriteLine(string.Format("1) {0:C}", 182.23));

// uses the provided culture
Console.WriteLine(string.Format(CultureInfo.InvariantCulture, "2) {0:C}", 182.23));

// spin up a thread - uses system settings
new Thread(() =>
    {
        Console.WriteLine(string.Format("3) {0:C}", 182.23));
    }).Start();

// spin up a thread - uses thread settings
var t = new Thread(() =>
{
    Console.WriteLine(string.Format("4) {0:C}", 182.23));
});

t.CurrentCulture = new CultureInfo("en-us");

t.Start();

Console.ReadLine();

CropperCapture[2]

You can see in the capture above lines 1 & 3 use the South African culture settings it gets from the operating system. What if I want to force say an American culture globally? There was no way before .NET 4.5 to do that.

What .NET 4.5 adds?

By merely adding one line to the top of the project, all threads, including the one we are in get the same culture:

CultureInfo.DefaultThreadCurrentCulture = new CultureInfo("en-us");

CropperCapture[1]

File attachments