Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Set specific culture for class

I have a class in C# which has various methods. I want to use en-US culture in all the methods in this class. Can I set the culture for a specific class?

Background: I have a List<object> and some of the object's are numbers and some are strings. I would like all the numbers written using US culture, but I don't know which items are numbers. The object class's ToString() seems to not take a culture argument.

like image 816
Chau Avatar asked Feb 23 '10 15:02

Chau


1 Answers

A class is a data structure, while localized string formatting is behavior. From a code/compiler perspective, the two things have nothing to do with eachother, and it doesn't make sense to set it on a "per class" basis. This problem belongs in the scope of the code that uses the class, or the code inside the class itself.

Global culture information is set per thread (using Thread.CurrentThread.CurrentCulture or CultureInfo.CurrentCulture). One thing you can do, is to wrap every method of the class in a culture set/restore. Since thread culture is for all purposes a global variable, this could get problematic if your class ever calls out somewhere else.

The best approach, if you want to specify a culture for your class to use, is to just have an instance of the culture to use as a class property, and then use the culture-specific overloads of most string/number formatting functions.

class MyClass {
    public CultureInfo Culture { get; set; }

    public void GetSomeString() {
        return new Int32().ToString(Culture);
    }
}

Edit: Taking a closer look at your question, I think what you want to do is something of the sort:

var lastCulture = Thread.CurrentThread.CurrentCulture;
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US");
try {
   // loop over list here
}
finally {
    Thread.CurrentThread.CurrentCulture = lastCulture;
}
like image 67
Alex J Avatar answered Sep 23 '22 05:09

Alex J