There is a comparator for sorting in the reverse order.

class Comp<T> : IComparer<T> where T : IComparable<T> { public int Compare(T x, T y) { return -x.CompareTo(y); //return y - x; } } 

Question: Is it possible to make it so that it is possible to return y - x as a result of the comparison, as in the commented section (this makes it difficult to make a generic type T)

  • I think no. But why bother? - DreamChild
  • @DreamChild interest. - pandal

2 answers 2

Not. Operators cannot be used with generic types, since they are static and cannot be restricted by using the interface.

As for the subtraction for comparison, and the unary minus - there may be problems due to overflow. Although the standard Enumerable.OrderByDescending already contains this bug: http://codeblog.jonskeet.uk/2015/03/02/backward-compatibility-pain/

PS: In fact, the subtraction method can be shoved by forcing to determine the types and look for the operator during the execution of the method, but this will be a very big impact on performance, especially given that comparators are usually used when sorting.

And the best way to do a reverse comparator is

 public int Compare(T x, T y) { return y.CompareTo(x); } 
  • ABOUT! Your code is better. - VladD
  • @VladD, only he is not quite mine - see the post on the link :) - Qwertiy

Such a possibility does not exist because at the current moment it is impossible to express in C # a constraint for a generic type that guarantees the existence of one or another operator. (However, support for this is discussed by the language development team.)

However, your code with subtraction is incorrect even if T = int . Imagine that x == int.MaxValue , y == -1 , then x - y will become negative due to overflow.

Correctly in the idea so:

 return -Math.Sign(x.CompareTo(y)); 
  • Nice to know good news. And if they also did it - it would be great at all :) - Qwertiy
  • @Qwertiy: C # 7 will be revolutionary, I hope. Here is a list of things discussed . - VladD
  • Unfortunately, much was also discussed under the sixth, and also under VB.NET, but much of what was discussed was rejected as a result. Such a fate may be the seventh to have ... - Qwertiy
  • @Qwertiy: By the way, you can also participate in the discussion process. It is open to all. - VladD