09 May 2012
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]

AttachmentSize
Package icon Culture Info Demo33.41 KB

Comments

The Morning Brew - Chris Alcock » The Morning Brew's picture

[...] .NET 4.5 Baby Steps, Part 8: AppDomain wide culture settings - Earlier this month Robert MacLean was posting a series looking at the new features and changes in .NET 4.5. The linked article here is part 8 of the series looking at a change in culture settings. The others in the series are worth checking out too. [...]

Nadav's picture

About time this was added...
This was one of the things that really bothered me about the way dot.net handled CultureInfo.
(Especially if you work with tasks and or async programing ...)

Nadav

Add new comment