Comparison<T> and Collection Sorting
April 17, 2005
After looking at Predicate<T> I thought it would be cool to take a squizz at the Comparison<T> generic delegate type and the Sort(…) method found on generic collections. Comparison<T> allows you to sort lists of items in the same way that you used to use an IComparer, the difference is that you can declare them inline with your method which means you don’t have proliferation of type definitions in your code (**).
Look at the first commented section, here I am simply sorting by the driver’s rating. In the second commented section I am doing a slightly more complex sort by sorting by rating AND THEN by the driver’s first name. For simple sorts you’d probably do it inline with the method call versus splitting it out into its own block, but for more complex sorting I would recommend defining it and stuffing the implementation into its own couple of lines of code.
You can download the code for this demo here.
** Note that while you don’t end up creating additional types in your code, the C# compiler actually produces a method and field for each anonymous method. This is a little bit different to what I observed with earlier versions of VS2005 which produced a whole extra type.
April 17, 2005 at 12:00 am
Cool stuff, Mitch, keep it coming!
April 18, 2005 at 12:00 am
Hey Mitch,
I haven’t got Beta 2 instaleld so I’m flying blind on this, but I think the kind of generated code depends on whether or not you access local variables from the containing method.
(1) If you do access variables declared in the containing method, then the anonymous delegate is generated as a new method in a new type, and the lcoal varaibles become fields in that new type.
(2) If you do not access variables declared in the containing methos, then the anonymous delegate is created as a method in the containing method’s type, and a field is used to store a reference t the delegate (necessary to keep the delegate alive after).
So the two things to be aware of are, in case (1) local variables become fields and hence performance can be iimpacted. Only likely to be noticeable in tight large loops.
In case (2) (and sometimes in case (1)) develpers need to be aware that the anonymous delegate that is being passed to a method outside the class can keep the class alive.
anyway, that’s based on earlier bits… Is this the same as you are seeing in Beta 2 ?
Thnx,
Bill
P.S. Hey for code camp, any thoughts on having a book swap ?
April 18, 2005 at 12:00 am
Hi Bill,
Yeah – thats probably why I didn’t see what I saw last time I ILDasm’d it. Good idea on the book swap let me think on it today and I’ll see if we can get the word out.