Skip to content

Instantly share code, notes, and snippets.

@hugoware
Created October 27, 2010 15:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hugoware/649238 to your computer and use it in GitHub Desktop.
Save hugoware/649238 to your computer and use it in GitHub Desktop.
Performs work in anonymous functions under a different context before switching back
// Quickly switch to a different culture to perform work without
// switching the entire thread
// Usage:
// Console.WriteLine("Starts in English : {0}", DateTime.Now);
//
// Culture.As(Culture.Type.German, () => {
// Console.WriteLine("Now in German : {0}", DateTime.Now);
// });
//
// Console.WriteLine("English again : {0}", DateTime.Now);
/// <summary>
/// Handles working in different cultures for periods of times
/// </summary>
public class Culture {
/// <summary>
/// Types of cultures to use
/// </summary>
public enum Type {
English,
German,
Spanish
}
/// <summary>
/// Performs work in a different culture
/// </summary>
public static void As(Culture.Type type, Action work) {
string culture = Culture._GetCultureString(type);
Culture.As(culture, work);
}
/// <summary>
/// Performs work in a different culture
/// </summary>
public static void As(string culture, Action work) {
culture = (culture ?? string.Empty).Trim();
//get the existing cultures to revert
var original = new {
culture = Thread.CurrentThread.CurrentCulture,
uiCulture = Thread.CurrentThread.CurrentUICulture
};
//create the new cultures to use
CultureInfo temporary = new CultureInfo(culture);
Thread.CurrentThread.CurrentCulture = temporary;
Thread.CurrentThread.CurrentUICulture = temporary;
//perform the work
try { work(); }
//and make sure to revert the culture
finally {
Thread.CurrentThread.CurrentCulture = original.culture;
Thread.CurrentThread.CurrentCulture = original.uiCulture;
}
}
//grabs the culture string from a type
private static string _GetCultureString(Culture.Type type) {
switch (type) {
case Type.German: return "de-DE";
case Type.Spanish: return "es-ES";
//add more cultures as needed
default: return "en-EN";
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment