When should I specify CurrentCulture or InvariantCulture and when should I leave it unspecified?

末鹿安然 提交于 2019-11-30 08:12:59

There is an inherent trade-off in play here.

At a minimum, you'll want to specify CultureInfo to use InvariantCulture whenever you are doing anything internal within your program. For example, using this with Serialization forces the data representation to always be the same, so you don't have to worry about internationalization issues with your internal data formats.

That being said, specifying this everywhere has some advantages - mainly in terms of forcing you to make sure you're handling this correctly. Internal program work vs. UI work needs to have a different culture specified (provided you want to properly localize your application). As a result, a complex program tends to require this to be specified everywhere, as leaving the "default" is dangerous at best, and tends to introduce bugs over time.

However, specifying this, as you noticed, tends to increase the size of your code, and potentially reduce the readability. This leads to the trade-off - readability and maintainability via shorter code vs. proper internationalization and localization and maintainability via being more explicit everywhere.

In my opinion, there is no "right" answer here - it really depends on your application. If your application is completely about presentation, and not doing a lot of data manipulation, especially not with any type of self-managed file storage, setting the current culture (and ui culture) once may be fine. I've found that more complicated applications tend to not work as well in this fashion, however, in which case the FxCop suggestions of specifying this everywhere seem more attractive.

The default is already the current culture as initialized by Windows. So using CultureInfo.CurrentCulture explicitly is just a waste of time. Any decent serialization format (including binary serialization and XML serialization) will serialize a DateTime in a culture invariant way.

Using a culture that is not the default is very dangerous. A thread will always be started with the default culture as specified by Windows and configured by the user when she installed Windows. .NET starts threadpool threads all the time and you'll risk getting a culture in that thread that is different from your main thread. Which can cause all manner of subtle problems. Like having a SortedList that suddenly isn't sorted anymore.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!