ArgumentOutOfRangeException when calling DateTime.ToString()
Recently I encountered a strange problem with one of my .NET applications when running on phones having the language set to Chinese. If started by clicking the executable file, the program would just crash without warning at startup. If started via Visual Studio debugger, the debugging session will be terminated shortly with the error message “The remote connection to the device has been lost” and the program crashes with no further error messages.
For the device to show a more detailed error message, I uninstalled the .NET Compact Framework version 2.0 that comes bundled with the device and let Visual Studio automatically install the framework before debugging in started. With this change, the exact error message pops up, showing an ArgumentOutOfRangeException when the program tries to call DateTime.ToString(). With some further investigation, I realized this seems to be an issue with the .NET Compact Framework when running on phones where the user has changed the default language in Regional Settings to Chinese. In all my test devices, the problem seems to only happen on HTC phones with the language set to Chinese (Singapore) and strangely does not occur when a different Chinese dialect (e.g. Chinese (Taiwan)) is used.
The problem may have to do with the fact that HTC phones allow user to switch between 西历 and Gregorian Calendar. On other phones that do not have this problem the option Calendar Type is grayed out, default to 西历, and thus cannot be changed if the localization is set to Chinese.
Interestingly, when this problem happens, a Try/Catch around the related code section does not always prevent the crash. If it does, further execution of the program may have erratic behaviour such as throwing mysterious ArgumentOutOfRangeException or returning wrong results when calculating date/time values.
Upgrading to .NET Compact 3.5 does not fix the problem.