12

I have a sorter which performs various comparisons. Resharper says I should change from String.CompareTo to String.CompareOrdinal. Does this really provide much benefit or is it something I should adjust the inspection rules for?

CompareTo:

config.Sort(delegate(configData data1, configData data2)
{
    if (data1.SettingName.Equals(data2.SettingName))
    {
        string m1 = data1.SettingMachine;
        string m2 = data2.SettingMachine;
        if (m1 == null)
            m1 = string.Empty;
        if (m2 == null)
            m2 = string.Empty;
        return m1.CompareTo(m2);
    }

    return data1.SettingName.CompareTo(data2.SettingName);
});

CompareOrdinal:

config.Sort(delegate(configData data1, configData data2)
{
    if (data1.SettingName.Equals(data2.SettingName))
    {
        string m1 = data1.SettingMachine;
        string m2 = data2.SettingMachine;
        if (m1 == null)
            m1 = string.Empty;
        if (m2 == null)
            m2 = string.Empty;
        return String.CompareOrdinal(m1, m2); ;
    }

    return String.CompareOrdinal(data1.SettingName, data2.SettingName);
});
Simon MᶜKenzie
  • 8,344
  • 13
  • 50
  • 77
Adam
  • 3,615
  • 6
  • 32
  • 51
  • The warning is "CompareTo is culture specific" – Nick Aug 13 '12 at 21:02
  • Also related: http://stackoverflow.com/questions/10941375/could-string-comparisons-really-differ-based-on-culture-when-the-string-is-guara – Nick Aug 13 '12 at 21:03
  • So from a resharper standpoint it looks like it is recommending it based off of keeping culture in mind – Adam Aug 13 '12 at 21:15

1 Answers1

17

Resharper is concerned that if you were to run your code on a system which was using a different default character encoding, the comparison could fail. CompareOrdinal is culture-invariant, thus removing the problem.

Simon MᶜKenzie
  • 8,344
  • 13
  • 50
  • 77
  • 1
    Yeah, it's really better. I've seen many times when string comparison has places "Bog" under "Bóg" or vice versa, just depending on the OS language, and there were then differences between the sorting order generated by the database and the client application.. Sometimes this is not important, but if you are generating i.e. a payment schedule, well.. :) – quetzalcoatl Aug 14 '12 at 00:11