Click here to Skip to main content
15,896,726 members
Articles / Programming Languages / C#

A CultureInfo switcher with Fluent syntax

Rate me:
Please Sign up or sign in to vote.
3.90/5 (4 votes)
20 Jul 2011CPOL2 min read 22.6K   198   9  
For purposes of Unit Testing in globalized applications, you could sometimes need to change the CurrentCulture to test methods against different languages. Here are a few classes that provide a Fluent syntax for switching to another culture.
using System;
using System.Globalization;
using System.Threading;

namespace Tests
{
    /// <summary>
    /// </summary>
    /// <remarks>
    /// </remarks>
    internal class SwitchCultureInfo: IDisposable
    {
        private readonly CultureInfo _original;

        /// <summary>
        /// Changes the current CultureInfo
        /// </summary>
        /// <param name="newCultureInfo"></param>
        public SwitchCultureInfo(CultureInfo newCultureInfo)
        {
            _original = Thread.CurrentThread.CurrentCulture;
            Thread.CurrentThread.CurrentCulture = newCultureInfo;
        }


        /// <summary>
        /// Changes the current CultureInfo
        /// </summary>
        /// <param name="cultureName"></param>
        public SwitchCultureInfo(string cultureName) : 
            this(new CultureInfo(cultureName))
        {}


        /// <summary>
        /// Restores the CultureInfo buffered in the constructor.
        /// </summary>
        public void Dispose()
        {
            Thread.CurrentThread.CurrentCulture = _original;
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Italy Italy
My name is Idalgo Cantelli. I'm a software developer skilled in .Net technologies. I work with .Net since February, 2002. I also have a strong experience as a technical trainer, having taught in more than thirty classroom courses. I'm MCTS and MCPD-EAD on .Net 2.0, planning an upgrade to 3.5.

Comments and Discussions