Jelle Druyts .NET Consultant
Just another ignorant weirdo from Antwerp, Belgium trying to make sense out of it all
Imagine a typed dataset of which you want to sort the rows in a special way according to a calculation on the column values. Sounds fairly complicated - but using the new generics and anonymous methods feature in C# Whidbey, it's pretty easy really:
MonitorItemData.MonitorItemsRow[] rows; // This array is already filled.Array.Sort<MonitorItemData.MonitorItemsRow>( rows, delegate( MonitorItemData.MonitorItemsRow row1, MonitorItemData.MonitorItemsRow row2 ) { // Calculate the absolute deviations of the individual monitor items. // Multiply by 10000 to increase the subtraction precision of the ints. int deviation1 = Math.Abs( 10000 * ( row1.ActualValue - row1.StandardValue ) / row1.StandardValue ); int deviation2 = Math.Abs( 10000 * ( row2.ActualValue - row2.StandardValue ) / row2.StandardValue ); // Sort descending according to the deviation. return deviation2 - deviation1; });
For the Array.Sort method, we're using a generic overload which takes a an array of the generic type T and a Comparison<T> delegate that can compare two instances of the generic type. But where is the Comparison delegate type mentioned? Nowhere - it's called type inference. So by looking at the signature on the anonymous method above, the compiler can make a well-educated "guess" about the type of the delegate and this baby will just compile and run. Cool? I think so!
Array.Sort
T
Comparison<T>
Comparison