Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to set a DLL to always follow CultureInfo.InvariantCulture by default, if not specified?

Tags:

c#

I have a lot of code in a class library that does not specify CultureInfo.InvariantCulture. For example in toString operations, toBool, toInt, etc.

Is there a way I can get set a property for the class library to always execute using CultureInfo.InvariantCulture, even if it is not explicitly specified everywhere in the code?

Sort of like a global switch?

It is not only messy to have to explicitly type it everytime, it makes my code less readable, and is a royal pain for example:

if (Convert.ToInt16(task.RetryCount, CultureInfo.InvariantCulture) <
            Convert.ToInt16(ConfigurationManager.AppSettings["TasksMaxRetry"], CultureInfo.InvariantCulture))
like image 504
JL. Avatar asked Dec 05 '25 21:12

JL.


2 Answers

While I agree that Mark's answer is the correct answer to the question posed; I don't think that switching the thread culture is a good design. It could introduce subtle bugs if other parts of the application, most likely the UI, depends on the threads current culture. Also, I would argue that explicitly stating the culture in Convert calls is a good design, that tells the reader of the code that the original programmer has made an active decision about which format to allow; and that the code is not just "working by coincidence".

You will most likely want to have many of your parse operations grouped together in the same class; perhaps one that deals with reading configuration. In that class, you could define a field to contain the culture you would like to use for parsing:

private static readonly IFormatProvider parseFormat = CultureInfo.InvariantCulture;

Then use that field in any calls to Convert methods or similar. Declaring the field as an IFormatProvider, together with a well chosen name, tells the reader of the code very explicitly, that this is a field used to define the parsing format. IMHO, it makes the intent of the code clearer.

Another way to do this would be to make your own Parse / Convert class, that wraps the Convert.ToXxx methods and calls them with the format you intend to use. Then you will have the desired benefit of not having to explicitly state the format in each call.

like image 146
driis Avatar answered Dec 07 '25 11:12

driis


I don't think so, but it is possible to set the CultureInfo on a per-thread basis:

Console.WriteLine(double.Parse("1.000"));
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
Console.WriteLine(double.Parse("1.000"));

Output on my machine (your output may vary depending on your current culture):

1000
1

Is this what you want?

like image 39
Mark Byers Avatar answered Dec 07 '25 11:12

Mark Byers