Search code examples
c#genericsdelegates

Link between Comparer<T>, IComparer<T> and Comparison<T>


I'm newbie to C#. I need to write a code which will sort an array of T. I ran into a problem with choosing comparing methods.
According to my task, I should provide methods, working with Comparer<T>, IComparer<T> and Comparison<T>.
I'm looking for a solution, which can bring one method to another, so I avoid repeating the same logic with each of Comparer<T>, IComparer<T> and Comparison<T>.

I know, that Comparison<T> may be 'recreated' to Comparer<T> with Comparer<T>.Create, but how to make Comparer<T> and IComparer<T> interchangeable?

So far, prototypes of methods look like this.

public T[] Sort<T>(T[] toSort) where T : System.IComparable<T>;
    
public T[] Sort<T>(T[] toSort, IComparer<T> comparer);
    
public T[] Sort<T>(T[] toSort, Comparer<T> comparer);
    
public T[] Sort<T>(T[] toSort, Comparison<T> comparison);

Solution

  • Comparer<T> implements the IComparer<T> interface (in simple terms - it is a IComparer<T>):

    public abstract class Comparer<T> : IComparer<T>, IComparer
    

    So it can be used anywhere IComparer<T> can be used without any effort. I.e. you can just remove public T[] Sort<T>(T[] toSort, Comparer<T> comparer); and you still will be able to pass instance of Comparer<T> as parameter for public T[] Sort<T>(T[] toSort, IComparer<T> comparer);.

    Read more: