Click here to Skip to main content
Click here to Skip to main content

Anonymous Methods - Behind the Scenes

By , 9 Feb 2011
Rate this:
Please Sign up or sign in to vote.

Introduction

I think one of the most mysterious things in the software development world is compilers. Let's talk about C# compiler specifically.

C# compiler was written in C++ for historical reasons. C# compiler takes source files, then generates IL code. But we don't know what's going on inside C# compiler when generating IL code. In this process, C# compiler also creates different kinds of new structures.

Anonymous Methods - Behind the Scenes

Anonymous methods provide us to define unnamed methods and most common usage of anonymous methods is delegates.

For example,

btnLambda.Click += (_sender, _args) =>
{
    MessageBox.Show("This is an anonymous function");
}; 

Simply, this statement adds an event handler to the button's click event. But what's going on behind the scenes? Does the compiler make extra translations?

Firstly, we open this application with reflector.

1.jpg

We see that the compiler has generated a different method and delegate named as <WindowLoaded>b__0 and CS$<>9__CachedAnonymousMethodDelegate1. This method includes anonymous method's inline statement.

2.jpg

If we put this event handler assignment into Loaded event of a WPF Window, we can see generated IL code like below:

3.jpg

Simply, in this method first, the compiler creates a delegate which takes generated static method as parameter and then adds this delegate as Button's click event handler.

Using Local Variables in Anonymous Methods

I think using local variables in anonymous methods is the most important feature of anonymous methods. If we add a delegate to an event as event handler explicitly, we can't use any local variables inside this method which assignment operation made in.

Let's demonstrate this scenario.

private void Window_Loaded(object sender, RoutedEventArgs e)
{
     int x = 10;
     double y = 198.30;
     btnLambda.Click += (_sender, _args) =>
     {
         MessageBox.Show(String.Format("This is an anonymous function 
             result={0}",(x*y)));
     };
}

In this method, anonymous method uses local variables which are defined in method that event handler assignment made in.

Now let's look at the new class view of the project with reflector again.

4.jpg

In this scenario, the compiler generates a new type named <>c__DisplayClass1. This type includes 2 fields which we used in anonymous method declaration and also includes a method declaration that performs actions we specified in anonymous method declaration as we discussed in the previous section.

5.jpg

Window_Loaded method in IL codes:

6.jpg

In this method firstly, compiler generates new <>c__DisplayClass1 object, then assigns field values. And finally, the compiler creates a delegate by giving method which locates in <>c__DisplayClass1 type and adds this delegate to button's Click event as event handler. If we use a local object reference in an anonymous method, the scenario will be the same. Compiler-generated type will include relevant fields in order to access used object.

Conclusion

As you see, compilers are really mysterious. When programming languages provide some new features, the compiler deals with some extra translations and makes the developer's life easier.

Maybe that's why I love compilers and programming languages. Smile | :)

Hope this helps !

History

  • 9th February, 2011: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

İlkay İlknur
Software Developer Innova
Turkey Turkey
İlkay İlknur has been working at Innova IT Solutions in Turkey.
Also he is a MCTS - WCF 4.0,Silverlight 4.0.
 
Generally,he writes articles about C#,WCF,WPF and Silverlight.
 
You can follow my blog at http://www.ilkayilknur.com/en
My twitter account http://twitter.com/ilkayilknur
Follow on   Twitter

Comments and Discussions

 
GeneralIL code Pinmemberalxxl14-Feb-11 22:19 
GeneralMy vote of 5 PinmemberBinoy Patel10-Feb-11 7:41 
GeneralPretty simple, but well explained and the more people that know about closures the better PinmvpSacha Barber9-Feb-11 22:36 
You should also point to this post, its very informative when working with closures (those dynamically created classes are called closures) :
 
http://marlongrech.wordpress.com/2010/06/02/closures-in-c-can-be-evil/[^]
 
http://codebetter.com/matthewpodwysocki/2008/09/12/side-effects-and-functional-programming/[^]
Sacha Barber
  • Microsoft Visual C# MVP 2008-2011
  • Codeproject MVP 2008-2011
Your best friend is you.
I'm my best friend too. We share the same views, and hardly ever argue
 
My Blog : sachabarber.net

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140415.2 | Last Updated 9 Feb 2011
Article Copyright 2011 by İlkay İlknur
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid