Using a CultureScope to switch to a specific Culture for a block of code
February 2, 2009 at 3:47 PM
—
Kevin Bosch
The .NET framework provides support for localization. Localization deals with customizing data and resources for specific culture or locale or language. Supporting localization is important for an application if the application is required to be customizable based on the respective culture. Now having to support multiple Cultures invariably means you should be testing your code running under multiple Cultures to ensure it behaves as expected. This is where the concept of the Culture Scope was conceived. Basically using Culture Scope it is possible to define a block of code to run under a specific Culture then revert back when done. Example:
// Set formatString for a currency so we can test diffrent Cultures
string formatString = "{0:c}";
double TestNumber = 123456.78;
// set the TestCulture to New Zealand
using (new CultureScope("en-NZ"))
{
string result = string.Format(formatString, TestNumber);
// here we assert that the result is formatted with a dollar $
Assert.AreEqual("$123,456.78", result);
}
// set the TestCulture to English - United Kingdom
using (new CultureScope("en-GB"))
{
// now make the same call as above with the same parameters..
string result = string.Format(formatString, TestNumber);
// Now assert the string is formatted with pound £
Assert.AreEqual("£123,456.78", result);
}
Note the the same code:
string result = string.Format(formatString, TestNumber);
is called twice with different CultureInfo passed to the scope the result is of a function in each scope yields a different result pending the Culture within the given scope The source for the CultureScope is really simple it implements the IDisposable pattern then on creation it keeps a copy of the starting CultureInfo such that it has the ability to roll back on completion. The full source is as follows:
[code:c#]
public class CultureScope : IDisposable
{
private CultureInfo _rollbackCulture;
private void CommonConstructor(CultureInfo cultureinfo)
{
if (cultureinfo != null)
{
_rollbackCulture = Thread.CurrentThread.CurrentCulture;
Thread.CurrentThread.CurrentCulture = cultureinfo;
}
else
{
throw new ArgumentNullException("cultureinfo", "Cannot set a null CultureInfo to the current thread");
}
}
public CultureScope(CultureInfo cultureinfo)
{
CommonConstructor(cultureinfo);
}
public CultureScope(string Culture)
{
CultureInfo cultureinfo = new CultureInfo(Culture);
CommonConstructor(cultureinfo);
}
public void Dispose()
{
Thread.CurrentThread.CurrentCulture = _rollbackCulture;
}
}
[code]