List.Sort in C#: comparer being called with null object

后端 未结 7 1229
攒了一身酷
攒了一身酷 2021-01-01 11:48

I am getting strange behaviour using the built-in C# List.Sort function with a custom comparer.

For some reason it sometimes calls the comparer class\'s Compare meth

7条回答
  •  佛祖请我去吃肉
    2021-01-01 12:38

    I too have come across this problem (null reference being passed to my custom IComparer implementation) and finally found out that the problem was due to using inconsistent comparison function.

    This was my initial IComparer implementation:

    public class NumericStringComparer : IComparer
    {
        public int Compare(string x, string y)
        {
            float xNumber, yNumber;
            if (!float.TryParse(x, out xNumber))
            {
                return -1;
            }
            if (!float.TryParse(y, out yNumber))
            {
                return -1;
            }
            if (xNumber == yNumber)
            {
                return 0;
            }
            else
            {
                return (xNumber > yNumber) ? 1 : -1;
            }
        }
    }
    

    The mistake in this code was that Compare would return -1 whenever one of the values could not be parsed properly (in my case it was due to wrongly formatted string representations of numeric values so TryParse always failed).

    Notice that in case both x and y were formatted incorrectly (and thus TryParse failed on both of them), calling Compare(x, y) and Compare(y, x) would yield the same result: -1. This I think was the main problem. When debugging, Compare() would be passed null string pointer as one of its arguments at some point even though the collection being sorted did not cotain a null string.

    As soon as I had fixed the TryParse issue and ensured consistency of my implementation the problem went away and Compare wasn't being passed null pointers anymore.

提交回复
热议问题