Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparer<T>.Default Property

Tags:

c#

This question comes from this Little Wonders: Comparer<T>.Default . I am wondering what the author wrote in the line:

If the type you want to compare already implements IComparable<T> or if the type is System.Nullable<T> where T implements IComparable, there is a class in the System.Collections.Generic namespace called Comparer<T> which exposes a property called Default that will create a singleton that represents the default comparer for items of that type.

So for example :

I have a class :

class Foo : IComparable<Foo> { ... }
public class FooComparer : IComparer<Foo> { ... }

Comparer class implemented as public abstract class Comparer<T> : IComparer, IComparer<T> . My question is how Default property works overall , what it does and how it works?

Thanks

like image 709
M3taSpl0it Avatar asked Feb 19 '13 14:02

M3taSpl0it


People also ask

What is the default equality Comparer?

Equals(T) for equality, otherwise it will use your Equals(object) method. This method defaults to reference equality as defined in the object class.

What is the default Comparer C#?

IComparable interface, then the default comparer is the IComparable. CompareTo(Object) method of that interface.

How does Comparer work C#?

Working of C# Compare()The Compare() method returns zero if the given two strings are equal in value. The Compare() method returns a value less than zero if, among the two strings given, the first string is preceding the second string in the order of sorting.

What is the Comparer class used for?

Briefly, Objects Comparer is an object-to-object comparer that allows us to compare objects recursively member by member and to define custom comparison rules for certain properties, fields, or types.


1 Answers

Comparer<T>.Default doesn't use your FooComparer class. It simply returns an instance of the internal class GenericComparer<T>.
This class has the constraint that T must implement IComparable<T> so it can simply delegate the calls to it Compare method to the Compare methods of the instances it gets passed.

Something like this:

internal class GenericComparer<T> : Comparer<T> where T : IComparable<T>
{
    public override int Compare(T x, T y)
    {
        if (x != null)
        {
            if (y != null)
                return x.CompareTo(y);
            return 1;
        }
        else
        {
            if (y != null)
                return -1;
            return 0;
        }
    }

    // ...
}
like image 134
Daniel Hilgarth Avatar answered Oct 06 '22 23:10

Daniel Hilgarth