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

Posted by cbp on Stack Overflow See other posts from Stack Overflow or by cbp
Published on 2009-06-22T08:18:26Z Indexed on 2010/03/23 15:23 UTC
Read the original article Hit count: 364

Filed under:
|
|

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 method with a null object as one of the parameters. But if I check the list with the debugger there are no null objects in the collection.

My comparer class looks like this:

public class DelegateToComparer<T> : IComparer<T>
{
    private readonly Func<T,T,int> _comparer;

    public int Compare(T x, T y)
    {
        return _comparer(x, y);
    }

    public DelegateToComparer(Func<T, T, int> comparer)
    {
        _comparer = comparer;
    }
}

This allows a delegate to be passed to the List.Sort method, like this:

mylist.Sort(new DelegateToComparer<MyClass>(
    (x, y) => { 
         return x.SomeProp.CompareTo(y.SomeProp); 
     });

So the above delegate will throw a null reference exception for the x parameter, even though no elements of mylist are null.

UPDATE: Yes I am absolutely sure that it is parameter x throwing the null reference exception!

UPDATE: Instead of using the framework's List.Sort method, I tried a custom sort method (i.e. new BubbleSort().Sort(mylist)) and the problem went away. As I suspected, the List.Sort method passes null to the comparer for some reason.

© Stack Overflow or respective owner

Related posts about c#

Related posts about list