Code inspection: String.CompareTo is culture-specific
Category: Common Practices and Code Improvements
ID: StringCompareToIsCultureSpecific
EditorConfig: resharper_string_compare_to_is_culture_specific_highlighting=[error|warning|suggestion|hint|none]
Language: C#
Requires SWA: No
tip
Similarly to the Specify a culture in string conversion explicitly, this inspection helps to avoid problems with running your code on machines with different culture settings.
When strings are compared using String.CompareTo
, comparison results may differ depending on the machine's locale. The canonical example is the Turkish where there is a lowercase dotless "ı" with the corresponding uppercase "I", and a lowercase "i" with an uppercase "İ" with the dot. As a result, the method below may return different results on machines with different culture settings.
To resolve this problem, ReSharper suggests adding the culture-invariant StringComparison.Ordinal
explicitly to the method call.
Suboptimal code
private int Foo(string s1, string s2){ //do something // 's1' will be compared to 's2' // according to the current // culture settings // Warning: String.CompareTo // is culture-specific return s1.CompareTo(s2);}
After the quick-fix
private int Foo(string s1, string s2){ //do something return String.Compare(s1, s2, StringComparison.Ordinal);}