According documentation:
System.Array.Sort<T>– sorts the elements in an entire System.Array using the System.IComparable generic interface implementation of each element of the System.Array.
Today I discover, that this code is compiling without any errors and warnings:
A []arr = new A[10];//A is not inheriting from IComparable !!
//initializing elements of arr
...
System.Array.Sort<A>(arr);
After execution I’m getting run-time error.
So why this code is compiling? I’m not big expert of C#, but I know, that C# generics supporting constraining syntax. Why constraints aren’t used for Array.Sort?
In compiles because there’s no constraint on
Tthat it has to implementIComparable<T>.I think the documentation is slightly confusing, because the array elements don’t actually have to implement
IComparable<T>for the sameTas the call. For example, this works fine:I think it’s more sensible to just say that the elements have to be comparable with each other “somehow”. For example, this is fine, even though nothing’s implementing the generic
IComparableinterface: