Why does IEnumerable <T> .Max not limit T?

If you call the extension method .Max() on IEnumerable<T> , and the objects inside do not implement IComparable , you get a System.ArgumentException: At least one object must implement IComparable.

Why does Max and similar methods prevent T implementing IComparable so that this problem can be caught at compile time rather than at run time?

+6
generics c # linq
source share
2 answers

I think because it is more flexible. For example, you may have an IEnumerable<object> that contains strings, in which case Max() can be called fairly safely, even though the Object type does not implement IComparable .

+6
source share

Comparisons ... fun. First, do you have the choice of IComparable<T> or IComparable - which would you choose? Currently (via Comparer<T>.Default ) it supports both options, but there isn’t "this or that" generic restriction ".

Then you get the question Nullable<T> ; it β€œtook off” the comparison, so whether it is comparable or not depends on T ; but again, Comparer<T>.Default deals with this for us ( Nullable<T> does not implement either IComparable or IComparable<T> ).

A plus; it saves the spread of general restrictions; as soon as you have such a restriction in the library code, it quickly infects the entire uplink code, making it hard.

+8
source share

All Articles