I've found out that inside the Array.Sort,
[ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail), SecurityCritical]
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern bool TrySZSort(Array keys, Array items, int left, int right);
gets called. Any ideas how this is implemented?
You can get a fairly reliable copy of the CLR source code from the SSCLI20 source distribution. It was published in 2005 and, at the time, was a pretty accurate copy of CLR version 2. Never found an obvious discrepancy.
That's moved on since then, already 7 years ago and a rather major CLR version update since. But TrySZSort() is still around, those low-level implementations are highly self-preserving. You'll find it declared in clr/src/vm/ecall.cpp and mapped to ArrayHelper::TrySZSort(), a C++ method declared in clr/src/vm/arrayhelpers.cpp
It is otherwise very boring, it just calls a template class method named ArrayHelpers<T>.QuickSort()
, specialized by array element type for value type elements.
Which is just the way Tony Hoare wrote it up 52 years ago. Albeit not in C++ ;)
You'll find the reason this code is written in C++ and not in C# in this answer.
Any ideas how this is implemented?
That method is implemented in native code, internal within the CLR itself. There are many methods like this on the very core, low level types. For example, quite a few of the methods on System.String
are flagged InternalCall and implemented in the common language runtime itself.
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