C # Set a specific culture for a class

I have a class in C # that has various methods. I want to use the en-US culture in all methods of this class. Is it possible to customize the culture for a particular class?

Background : I have a List<object> , and some of the object are numbers, and some are strings. I would like all numbers to be written using American culture, but I don’t know which elements are numbers. The object class ToString() does not seem to accept a culture argument.

+4
source share
2 answers

A class is a data structure, and localized string formatting is behavior. From a code / compiler point of view, these two things have nothing to do with eachother, and it makes no sense to set it based on "for each class." This issue relates to the scope of the code using the class, or to the code within the class itself.

Global culture information is set for each thread (using Thread.CurrentThread.CurrentCulture or CultureInfo.CurrentCulture ). One thing you can do is wrap each class method in a set / restore culture. Since the thread culture for all purposes is a global variable, this can cause problems if your class ever calls somewhere else.

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

 class MyClass { public CultureInfo Culture { get; set; } public void GetSomeString() { return new Int32().ToString(Culture); } } 

Edit: Having examined your question in more detail, I think you want to do something like:

 var lastCulture = Thread.CurrentThread.CurrentCulture; Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); try { // loop over list here } finally { Thread.CurrentThread.CurrentCulture = lastCulture; } 
+5
source

You can try pouring your elements and calling ToString on the resulting element, specyfing localizationa (catching InvalidCastException when this happens, and handle it accordingly), as this is allowed in a string or number. The solution is, at best, smelly, but workable.

0
source

Source: https://habr.com/ru/post/1302134/


All Articles