News, code, articles, rants; a daily dose of programming rigmarole.

Wednesday, February 14, 2007

Anonymous Methods - Perfect Stranger Or Close Relative?

Since most of the world (minus those currently under rocks or archaic cave dwellers) knows what anonymous methods are, I won't spend too much time analyzing them here. I did however come across something interesting when analyzing the IL of an assembly with a class that uses an anonymous method for sorting a collection. First we'll take a look at code and it's IL after compilation without an anonymous method, and then we'll try to put a face on the anonymity of anonymous methods.

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 = new 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 ){

return d1.CompareTo( d2 );
}*/
dates.Sort( this.Sort );
}

private int Sort( DateTime d1, DateTime d2 ){
return d1.CompareTo( d2 );
}
}

And here's its IL (ildasm.exe):










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 = new 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:

Anonymous said...

If you would like to learn more about recursion read the beginning of this comment.