Anonymous IComparer implementation

As indicated in one of the comments below, .Net 4.5 allows this via a static method on the Comparer<> class, e.g. comparing two objects based on the value of a property in the class:

var comparer = Comparer<KilowattSnapshot>.Create( 
        (k1, k2) => k1.Kilowatt.CompareTo(k2.Kilowatt) );

Obviously this can be used inline rather than assigned to a variable.


The .NET framework version 4.5 provides the method Comparer.Create(Comparison) to create comparers based on a specified comparison delegate (which can be a lambda function). However people who are working with earlier versions of .NET will probably need to implement something similar themselves.


Even though you can't create anonymous classes that implement interfaces, you can usually use the Comparison Delegate instead of the IComparer Interface in most cases (like sorting, etc.):

Array.Sort(arr, (x, y) => 1);

Also there are some built-in implementations of IComparer like the Comparer Class or the StringComparer Class...

Tags:

C#