LINQ OrderBy – using Comparer<T>.Create and F#’s Object Expressions

.Net 4.5 intro­duced a handy lit­tle new method Comparer<T>.Create to aid the cre­ation of bespoke com­par­ers, which is great because it means that you don’t have to define a new Com­par­er class when it is going to be need­ed once.

In case you’re won­der­ing, it’s still not pos­si­ble to define anony­mous imple­men­ta­tion of inter­faces in C#, but with Comparer<T>.Create you can at least cre­ate a bespoke instance of IComparer<T> from an anony­mous method:

As a side, you can also apply the same tech­nique for oth­er sin­gle method inter­faces your­self, for instance, if you were hap­py to ignore the exis­tence of the Zip exten­sion method for the sake of the exam­ple, you could define your own Zip exten­sion method which takes in an instance of an IZipper<T, U, V>:

Whilst we’re on the top­ic of anony­mous inter­face imple­men­ta­tion. F# has a nice lit­tle fea­ture call Object Expres­sions, it pro­vides a mech­a­nism for cre­at­ing anony­mous types that are based on exist­ing base type, inter­face, or set of inter­faces, and for the two exam­ples, here’s how that solu­tion might look in F#:

Notice that there’s no need for an explic­it imple­men­ta­tion class for IZipper<T, U, V> inter­face at all using Object Expres­sions and how much less code you end up writ­ing with F#! So seri­ous­ly, why aren’t you check­ing out F# already!? Winking smile