Search code examples
c#.neticomparableicomparer

Is implementing IComparable<T> sufficient for sorting or do I need to also implement IComparer?


Is it sufficient to Implement IComparable<T> for an object of my definition that I want to have in a list to be sorted?

For e.g I have this class definition

public sealed class StreamInfo : ICloneable, IExtensibleDataObject, IEquatable<StreamInfo>, IComparable<StreamInfo>

with 4 properties (1 string, 1 enum, and 2 ulong). I use these 4 properties to implement CompareTo function

public int CompareTo(StreamInfo other)
{
// details of implementation irrelevant to question
}

Somewhere else in the codebase, I maintain a list of StreamInfo.

List<StreamInfo> StreamInfoObj;

I would like to Sort the list using the Sort call:

Is the default Comparer, the one I implemented in the StreamInfo class by means of CompareTo above? Or do I still need to implement a class that inherits from IComparer and pass that to the Sort method? Just like the example below? Or is that unnecessary?

For example:

public sealed class OrderStreamsInfoAscending : IComparer<StreamInfo>
    {
        public int Compare(StreamInfo x, StreamInfo y)
        {
            if (x == null && y == null)
            {
                return 0;
            }
            else if (x == null)
            {
                return 1;
            }
            else if ( y == null)
            {
                return -1;
            }

            var result = x.CompareTo(y);
            return result;
        }
    }

Thank you

enter image description here


Solution

  • If you use Sort() method (without parameters), List class will use the default comparer, and if your class implements IComparable<T>, the List class will use that implementation.

    If you use Sort(IComparer<T>) – then the List class will use the IComparer<T> implementation, and ignore IComparable<T> implementation (if your class implements it).