Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resharper recommends changing CompareTo to CompareOrdinal

Tags:

c#

resharper

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);
});
like image 824
Adam Avatar asked Aug 13 '12 20:08

Adam


1 Answers

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.

like image 148
Simon MᶜKenzie Avatar answered Nov 05 '22 12:11

Simon MᶜKenzie