Here's the code without anonymous methods:
using System;
using System.Collections.Generic;
public class SortMan{
public static void Main( string[] args ){
SortMan s = new SortMan();
s.Test_Sort();
}
public void Test_Sort(){
List
dates.Add( DateTime.Now );
dates.Add( DateTime.Now.AddDays( -30 ) );
dates.Add( DateTime.Now.AddDays( -120 ) );
dates.Add( DateTime.Now.AddDays( -5 ) );
/*delegate( DateTime d1, DateTime d2 ){
}*/
dates.Sort( this.Sort );
}
private int Sort( DateTime d1, DateTime d2 ){
return d1.CompareTo( d2 );
}
}

Obviously our 'Sort' method is a member of our 'SortMan' class, just like any other method we would write in any other normal class. What about using an anonymous method?
Here's the code for our 'SortMan' class with an anonymous method:
using System;
using System.Collections.Generic;
public class SortMan{
public static void Main( string[] args ){
SortMan s = new SortMan();
s.Test_Sort();
}
public void Test_Sort(){
List
dates.Add( DateTime.Now );
dates.Add( DateTime.Now.AddDays( -30 ) );
dates.Add( DateTime.Now.AddDays( -120 ) );
dates.Add( DateTime.Now.AddDays( -5 ) );
dates.Sort( delegate( DateTime d1, DateTime d2 ){ return d1.CompareTo( d2 ); });
}
}
And finally here's the IL for this compiled assembly:

It's quite interesting to note that our "anonymous" method actually compiles as a static field in our SortMan class, with a local static method as its target! This "anonymity" appears to be nothing more than syntactical sugar to make it appear is if you don't really need a delegate instance, when in fact the compiler is creating a static delegate field variable for you, with a local static method as its target.
Anonymous methods make for clean syntax, but they are far from anonymous, and actually become a relative of the class they live inside.

1 comment:
If you would like to learn more about recursion read the beginning of this comment.
Post a Comment