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 isSystem.Nullable<T>
where T implementsIComparable
, there is a class in the System.Collections.Generic namespace calledComparer<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
Equals(T) for equality, otherwise it will use your Equals(object) method. This method defaults to reference equality as defined in the object class.
IComparable interface, then the default comparer is the IComparable. CompareTo(Object) method of that interface.
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.
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.
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;
}
}
// ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With