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 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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With