System.Comparison <T> understanding

List<T>.Sort() method has 3 overloads.

One of them is the following

 System.Collections.Generic.List<T>.Sort(System.Comparison<T>) 

When looking at Comparison<T> I thought it should be a class that is derived from the Comparison<T> class. (Normal interpretation of parameters)

But the following works very well and says it uses the above overload.

  public static void Main(string[] args) { List<Int32> collection = new List<Int32>(); collection.Add(20); collection.Add(270); collection.Add(30); collection.Add(90); collection.Add(40); collection.Add(18); collection.Add(100); collection.Sort(MyComparer.CompareWithCase); foreach (Int32 s in collection) Console.WriteLine(s); } public static int CompareWithCase(int i1, int i2) { return i1.ToString().CompareTo(i2.ToString()); } 

I gave the delegate a static method instead of Comparison<T> . How it works?

+6
source share
2 answers

System.Comparison<T> is defined as follows:

 public delegate int Comparison<in T>(T x, T y); 

This means delegate , not class. A method that takes a delegate as a parameter actually takes a method, not an instance of the comparison class.

This code can be rewritten as follows using a lambda expression:

 collection.Sort((i1, i2) => i1.ToString().CompareTo(i2.ToString())); 

The following snippet can better explain what is happening:

 public static class TestClass { public static void Main(string[] args){ Comparison<Int32> comparisonDelegate = CompareWithCase; //We now can use comparisonDelegate as though it is a method; int result = comparisonDelegate(1,2); } public static int CompareWithCase(int i1, int i2) { return i1.ToString().CompareTo(i2.ToString()); } } 
+9
source share

System.Comparison<T> is a delegate.

 public delegate int Comparison<in T>( T x, T y ) 

The signature of your CompareWithCase method makes it a perfectly assignable Comparison<int> .

Note that without entering text, your Sort call would have to be written as:

  collection.Sort(new Comparison<int>(MyComparer.CompareWithCase)); 

FYI, the remaining 2 overloads of List<T>.Sort are awaiting implementation of IComparer<T>

+1
source share

All Articles