2

I am writing a console application in C# which makes heavy use of string comparisons as well as formatting and parsing of numbers, which are read from and written to text files.

Ideally the program should behave exactly the same on every computer, however after testing it on a computer with a different locale I realized that mentioned functionality in C# automatically uses the format of the current locale. This is unfortunate since the locale of the system leads to changes in behaviour of my program and even to program crashes (i.e. when parsing numbers with the wrong - system specific - decimal separator).

I'm looking for a way to tell the compiler/program to ignore the current locale program-wide and use the default/english one instead.

I've seen mentioned solutions which can change the default locale for a thread.

I'm not sure how that works out with using linq, parallel foreach etc. so ideally I'd just like to set the english/default locale for the entire program to avoid any accidents. How can I do that?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Askaga
  • 6,061
  • 5
  • 25
  • 49
  • 1
    Most parsing and formatting methods in C# have an overload that takes an `IFormatProvider` and you could use `CultureInfo.InvariantCulture` to specify that you do not want to use the current culture for the parsing and formatting. – juharr Jul 20 '15 at 18:16
  • @juharr: That would hardly be a good application of the DRY principle, and would also be very error prone. In a program with dozens of the mentioned string operations you're bound to forget to add the format provider sometimes. – Askaga Jul 21 '15 at 07:58
  • If you use Code Analysis there is a rule that will flag them. – juharr Jul 21 '15 at 14:21

1 Answers1

2

Check out: Set default thread culture for all thread?

But the long and short of it is that it is set with the CultureInfo.DefaultThreadCurrentCulture property, per https://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo.defaultthreadcurrentculture.aspx

Community
  • 1
  • 1
Tripp Kinetics
  • 5,178
  • 2
  • 23
  • 37
  • That's it. But weirdly enough, CultureInfo.DefaultThreadCurrentCulture only seems to work if I also additionally set the running thread's culture as well. If I set only one of the two it still won't work... – Askaga Jul 21 '15 at 07:54
  • That just seems like a thread reads that property on startup, so a thread which is already created might not. But I'm just speculating. – Tripp Kinetics Jul 21 '15 at 13:12