vrijdag 21 augustus 2015

Set and reset CultureInfo inside a using block

Sometimes you want to set a specific CultureInfo, do something and afterwards reset to the original CultureInfo. We wanted to do that when rendering a pdf, which had to work with dates in the correct format.

So what we did was this:

var originalCultureInfo = Thread.CurrentThread.CurrentCulture;
var culture = new CultureInfo("fr-FR");
Thread.CurrentThread.CurrentCulture = culture;
RenderPdf();
Thread.CurrentThread.CurrentCulture = originalCultureInfo;


But that can be made a lot simpler, with less risk of forgetting to reset the CurrentCulture on the last line:

using (new CustomCulture("fr-FR"))
{
   RenderPdf();
}

The key is writing a CustomCulture class that inherits from IDisposable:

public class CustomCulture : IDisposable
{
   readonly CultureInfo _originalCultureInfo;

   public CustomCulture(string name)
   {
      _originalCultureInfo = Thread.CurrentThread.CurrentCulture;
      Thread.CurrentThread.CurrentCulture = new CultureInfo(name);
   }

   public void Dispose()
   {
      Thread.CurrentThread.CurrentCulture = _originalCultureInfo;
   }
}

Geen opmerkingen:

Een reactie plaatsen