views:

378

answers:

2

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.

A: 

You may try casting your items, and invoking ToString on the resulting item, specyfing localizationa (catching InvalidCastException when it occurs and handling it apropriately), as it's permitted in string or number. Solution is smelly at best, but workable.

Bolek Tekielski
+3  A: 

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;
}
Ilia Jerebtsov
@llia: It seems like that the property CurrentCulture of CultureInfo is read-only :(
Chau
This code cannot work as given.
Hans Passant
@llia, nobugz: The Thread.CurrentThread.CurrentCulture works though and I have chosen that solution. Thanks alot for your replies :)
Chau
You're right, my bad. Using `Thread.CultureInfo` is the correct way.
Ilia Jerebtsov