<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Coffee, Code and Chocolate &#187; Delegates</title>
	<atom:link href="http://blog.ganeshzone.net/blog/index.php/tag/delegates/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.ganeshzone.net/blog</link>
	<description>throw new Exception(&#34;#fail&#34;);</description>
	<lastBuildDate>Mon, 26 Jul 2010 19:45:49 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Differences between Events and delegates</title>
		<link>http://blog.ganeshzone.net/blog/index.php/2009/12/differences-between-events-and-delegates/</link>
		<comments>http://blog.ganeshzone.net/blog/index.php/2009/12/differences-between-events-and-delegates/#comments</comments>
		<pubDate>Sat, 26 Dec 2009 21:33:15 +0000</pubDate>
		<dc:creator>Ganesh Ranganathan</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Microsoft]]></category>
		<category><![CDATA[Visual STudio 2008]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[Delegates]]></category>

		<guid isPermaLink="false">http://blog.ganeshzone.net/blog/?p=710</guid>
		<description><![CDATA[<p style="text-align: justify;">Events and Delegates are quite tied together in .NET, but there are differences in terms of usage. Events are implemented through delegates, but they are not quite interchangeable. The event keyword is an access modifier on the delegate which restricts its usage outside the class which it belongs to.</p>
<p style="text-align: justify;">First the similarities. [...]]]></description>
			<content:encoded><![CDATA[<p style="text-align: justify;">Events and Delegates are quite tied together in .NET, but there are differences in terms of usage. Events are implemented through delegates, but they are not quite interchangeable. The event keyword is an access modifier on the delegate which restricts its usage outside the class which it belongs to.</p>
<p style="text-align: justify;">First the similarities. See the below code, which declares a delegate and creates objects for it with and without the event modifier. Then uses both of them, without any difference whatsoever.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">    <span style="color: #FF0000;">class</span> Test
    <span style="color: #000000;">&#123;</span>
        <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">delegate</span> <span style="color: #0600FF;">void</span> MyDelegate<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> _someRandomMessage<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">//One is a delegate while other is an event.</span>
        <span style="color: #0600FF;">public</span> MyDelegate _mydelObj<span style="color: #008000;">;</span>
        <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">event</span> MyDelegate _myeventObj<span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #0600FF;">public</span> Test<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#123;</span>
            _mydelObj <span style="color: #008000;">=</span> s <span style="color: #008000;">=&amp;</span>gt<span style="color: #008000;">;</span> Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Delegate Invoked: &quot;</span> <span style="color: #008000;">+</span> s<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            _myeventObj <span style="color: #008000;">=</span> s <span style="color: #008000;">=&amp;</span>gt<span style="color: #008000;">;</span> Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Event Invoked: &quot;</span> <span style="color: #008000;">+</span> s<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> TestDelegates<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#123;</span>
            _mydelObj.<span style="color: #0000FF;">Invoke</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;I am a delegate&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            _myeventObj.<span style="color: #0000FF;">Invoke</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;I am an event&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span></pre></div></div>

<p style="text-align: justify;">The main difference starts when you access events outside of the class they were declared in. I created one more class SomeOtherClass (very unimaginative!!) and invoked the public delegate objects from this. When its a plain delegate object, there is no restriction on resetting the invocation list, adding to it, removing from it and also invoking the delegate itself. But try doing that to the event object, and you the compiler will throw the <em><strong>The event &#8216;EventsAndDelegates.Test._myeventObj&#8217; can only appear on the left hand side of += or -= (except when used from within the type &#8216;EventsAndDelegates.Test&#8217;)</strong></em></p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">    <span style="color: #FF0000;">class</span> SomeOtherClass<span style="color: #000000;">&#123;</span>
        Test _testObj <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Test<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #0600FF;">public</span> SomeOtherClass<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            _testObj._mydelObj <span style="color: #008000;">+=</span> s <span style="color: #008000;">=&amp;</span>gt<span style="color: #008000;">;</span> Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Calling from Outside class: &quot;</span><span style="color: #008000;">+</span>s<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            _testObj._myeventObj <span style="color: #008000;">+=</span> s <span style="color: #008000;">=&amp;</span>gt<span style="color: #008000;">;</span> Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Calling Event from Outside class &quot;</span> <span style="color: #008000;">+</span> s<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #008080; font-style: italic;">//The below code wont work. An event's invocation list cannot be accessed</span>
            <span style="color: #008080; font-style: italic;">//from outside. It can be added to or removed from.</span>
            _testObj._myeventObj <span style="color: #008000;">=</span> s <span style="color: #008000;">=&amp;</span>gt<span style="color: #008000;">;</span> Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Trying to reset the invocation list&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> InvokeBaseDelegate<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #000000;">&#123;</span>
            _testObj._mydelObj<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Delegate Invoked&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #008080; font-style: italic;">//This will throw an error. An event cannot be triggered from anyother type</span>
            <span style="color: #008080; font-style: italic;">//other than the one which it belongs to</span>
            _testObj._myeventObj<span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Event Triggered&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span></pre></div></div>

<p>This key difference is due to the way events and delegates are exposed outside the class which they are declared in. There is an extra IL declaration for an event object which declares two accessors add and remove for the event. Only these are accessible outside the class.</p>

<div class="wp_syntax"><div class="code"><pre class="cil" style="font-family:monospace;"><span style="color:maroon;font-weight:bold;">.event</span> EventsAndDelegates.Test/MyDelegate _myeventObj
<span style="color: #006400;">&#123;</span>
  <span style="color:maroon;font-weight:bold;">.addon</span> <span style="color:blue;font-weight:bold;">instance</span> <span style="color:purple;font-weight:bold;">void</span> EventsAndDelegates.Test::<span style="color: #000033;">add__myeventObj</span><span style="color: #006400;">&#40;</span><span style="color:blue;font-weight:bold;">class</span> EventsAndDelegates.Test/MyDelegate<span style="color: #006400;">&#41;</span>
  <span style="color:maroon;font-weight:bold;">.removeon</span> <span style="color:blue;font-weight:bold;">instance</span> <span style="color:purple;font-weight:bold;">void</span> EventsAndDelegates.Test::<span style="color: #000033;">remove__myeventObj</span><span style="color: #006400;">&#40;</span><span style="color:blue;font-weight:bold;">class</span> EventsAndDelegates.Test/MyDelegate<span style="color: #006400;">&#41;</span>
<span style="color: #006400;">&#125;</span> <span style="color:gray;font-style:italic;">// end of event Test::_myeventObj</span></pre></div></div>

<p style="text-align: justify;">When this is accessed in <em>SomeOtherClass</em>, the Delegate.Combine method used to add to the delegate object&#8217;s invocation list is not available for the event and the only alternatives are the add and remove accessors. Similarly the Invoke method is not available outside the class because of which the events cant be triggered.</p>

<div class="wp_syntax"><div class="code"><pre class="cil" style="font-family:monospace;"><span style="color:maroon;font-weight:bold;">.method</span> <span style="color:blue;font-weight:bold;">public</span> <span style="color:blue;font-weight:bold;">hidebysig</span> <span style="color:blue;font-weight:bold;">specialname</span> <span style="color:blue;font-weight:bold;">rtspecialname</span>
        <span style="color:blue;font-weight:bold;">instance</span> <span style="color:purple;font-weight:bold;">void</span>  <span style="color:maroon;font-weight:bold;">.ctor</span><span style="color: #006400;">&#40;</span><span style="color: #006400;">&#41;</span> <span style="color:blue;font-weight:bold;">cil</span> <span style="color:blue;font-weight:bold;">managed</span>
<span style="color: #006400;">&#123;</span>
<span style="color:gray;font-style:italic;">//Removed for Brevity</span>
  IL_0035:  <span style="color:blue;">ldsfld</span>     <span style="color:blue;font-weight:bold;">class</span> EventsAndDelegates.Test/MyDelegate EventsAndDelegates.SomeOtherClass::'CS$&amp;lt;&amp;gt;<span style="color: #00008B;">9</span>__CachedAnonymousMethodDelegate2'
  IL_003a:  <span style="color:blue;">call</span>       <span style="color:blue;font-weight:bold;">class</span> <span style="color: #006400;">&#91;</span>mscorlib<span style="color: #006400;">&#93;</span>System.Delegate <span style="color: #006400;">&#91;</span>mscorlib<span style="color: #006400;">&#93;</span>System.Delegate::<span style="color: #000033;">Combine</span><span style="color: #006400;">&#40;</span><span style="color:blue;font-weight:bold;">class</span> <span style="color: #006400;">&#91;</span>mscorlib<span style="color: #006400;">&#93;</span>System.Delegate,
                                                                                          <span style="color:blue;font-weight:bold;">class</span> <span style="color: #006400;">&#91;</span>mscorlib<span style="color: #006400;">&#93;</span>System.Delegate<span style="color: #006400;">&#41;</span>
  IL_003f:  <span style="color:blue;">castclass</span>  EventsAndDelegates.Test/MyDelegate
<span style="color:gray;font-style:italic;">//Removed for brevity</span>
  IL_0067:  <span style="color:blue;">ldsfld</span>     <span style="color:blue;font-weight:bold;">class</span> EventsAndDelegates.Test/MyDelegate EventsAndDelegates.SomeOtherClass::'CS$&amp;lt;&amp;gt;<span style="color: #00008B;">9</span>__CachedAnonymousMethodDelegate3'
<span style="color:gray;font-style:italic;">//Notice the add_ accessor being called instead of the Delegate.Combine method</span>
  IL_006c:  <span style="color:blue;">callvirt</span>   <span style="color:blue;font-weight:bold;">instance</span> <span style="color:purple;font-weight:bold;">void</span> EventsAndDelegates.Test::<span style="color: #000033;">add__myeventObj</span><span style="color: #006400;">&#40;</span><span style="color:blue;font-weight:bold;">class</span> EventsAndDelegates.Test/MyDelegate<span style="color: #006400;">&#41;</span>
  IL_0071:  <span style="color:blue;">ret</span>
<span style="color: #006400;">&#125;</span> <span style="color:gray;font-style:italic;">// end of method SomeOtherClass::.ctor</span></pre></div></div>

<p style="text-align: justify;">It makes sense to restrict an event&#8217;s invocation list from an outside class. For example, if your application makes use of a public API which polls for the weather at a location and raises an event when there is going to be heavy snow. Someone in your team might have subsribed to the event to send out notifications to employees take caution while travelling. However, your need to subscribe to the event could be totally different. In that case if you use the <strong>=</strong> sign instead of the <strong>+=</strong> while assigning a handler, the previous code for sending out notifications would not work. Needless to say, there would be a lot of pi**ed off employees baying for your blood the next day.</p>
<p style="text-align: justify;">Apart from this, there is one more difference between delegates and events while declaring them in an interface. An interface cannot contain delegate objects, however they can contain events. If you try to do so, you would get an error <strong><em>Interfaces cannot contain fields.</em></strong></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.ganeshzone.net/blog/index.php/2009/12/differences-between-events-and-delegates/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Anonymous methods and captured variables in C# 2.0</title>
		<link>http://blog.ganeshzone.net/blog/index.php/2009/12/anonymous-methods-and-captured-variables-in-c-2-0/</link>
		<comments>http://blog.ganeshzone.net/blog/index.php/2009/12/anonymous-methods-and-captured-variables-in-c-2-0/#comments</comments>
		<pubDate>Wed, 23 Dec 2009 20:54:19 +0000</pubDate>
		<dc:creator>Ganesh Ranganathan</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Microsoft]]></category>
		<category><![CDATA[Visual STudio 2008]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[Anonymous methods]]></category>
		<category><![CDATA[Delegates]]></category>

		<guid isPermaLink="false">http://blog.ganeshzone.net/blog/?p=679</guid>
		<description><![CDATA[<p style="text-align: justify;">Anonymous methods are a convenient way of using delegates in .NET 2.0 and above. For e.g. if we use a delegate for a simple 2-3 line functionality, declaring a separate method and then passing the target to the delegate seems like overkill. Anonymous methods provide an easy way out, just declare the body [...]]]></description>
			<content:encoded><![CDATA[<p style="text-align: justify;">Anonymous methods are a convenient way of using delegates in .NET 2.0 and above. For e.g. if we use a delegate for a simple 2-3 line functionality, declaring a separate method and then passing the target to the delegate seems like overkill. Anonymous methods provide an easy way out, just declare the body of the method after the delegates declaration and you have no need to write a seperate method.</p>
<p style="text-align: justify;">Anonymous methods are a compiler feature. Hence, from the CLR&#8217;s point of view there is nothing anonymous about it. The C# compiler generates a method with your delegate declaration and adds it to the invocation list for the delegate. Here is some sample code.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;"> <span style="color: #FF0000;">class</span> TestClass
    <span style="color: #000000;">&#123;</span>
        <span style="color: #FF0000;">delegate</span> <span style="color: #0600FF;">void</span> writeToScreen<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> _inpar<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #0600FF;">void</span> TestDelegates<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            <span style="color: #008080; font-style: italic;">//1.1 way of doing things. Notice the seperate method.</span>
            writeToScreen _delObj <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> writeToScreen<span style="color: #000000;">&#40;</span><span style="color: #008000;">new</span> TestClass<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>.<span style="color: #0000FF;">NamedMethod</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">//2.0 way of calling it</span>
            _delObj <span style="color: #008000;">+=</span> <span style="color: #FF0000;">delegate</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> _inpar<span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Anonymous method says: &quot;</span><span style="color: #008000;">+</span>_inpar<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #000000;">&#125;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">//Lets invoke the delegate</span>
            _delObj.<span style="color: #0000FF;">Invoke</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Hello World&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> NamedMethod<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> _inpar<span style="color: #000000;">&#41;</span>
        <span style="color: #000000;">&#123;</span>
            Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Named method says: &quot;</span> <span style="color: #008000;">+</span> _inpar<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #000000;">&#125;</span>
    <span style="color: #000000;">&#125;</span></pre></td></tr></table></div>

<p style="text-align: justify;">In the above code, the 1.1 way would have you scrambling to find the definition of the NamedMethod,  but in second delegate its simpler and far more easier to understand. In the IL, the compiler generates a method for the anonymous block of code that you write.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="cil" style="font-family:monospace;"><span style="color:maroon;font-weight:bold;">.method</span> <span style="color:blue;font-weight:bold;">private</span> <span style="color:blue;font-weight:bold;">hidebysig</span> <span style="color:blue;font-weight:bold;">static</span> <span style="color:purple;font-weight:bold;">void</span>  'b__0'<span style="color: #006400;">&#40;</span><span style="color:purple;font-weight:bold;">string</span> _inpar<span style="color: #006400;">&#41;</span> <span style="color:blue;font-weight:bold;">cil</span> <span style="color:blue;font-weight:bold;">managed</span>
<span style="color: #006400;">&#123;</span>
  <span style="color:maroon;font-weight:bold;">.custom</span> <span style="color:blue;font-weight:bold;">instance</span> <span style="color:purple;font-weight:bold;">void</span> <span style="color: #006400;">&#91;</span>mscorlib<span style="color: #006400;">&#93;</span>System.Runtime.CompilerServices.CompilerGeneratedAttribute::<span style="color:maroon;font-weight:bold;">.ctor</span><span style="color: #006400;">&#40;</span><span style="color: #006400;">&#41;</span> = <span style="color: #006400;">&#40;</span> 01 00 00 00 <span style="color: #006400;">&#41;</span>
<span style="color:gray;font-style:italic;">//removed for brevity</span>
  IL_0010:  <span style="color:blue;">ret</span>
<span style="color: #006400;">&#125;</span>
<span style="color:gray;font-style:italic;">// end of method TestClass::'b__0'</span></pre></td></tr></table></div>

<p>So far so good, but anonymous methods bring more questions to the table. How are variables in the outer scope treated? Can they be accessed? Yes they can and they have a fancy name as well &#8211; Captured variables. Here is some code for it.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
</pre></td><td class="code"><pre class="csharp" style="font-family:monospace;">            <span style="color: #FF0000;">int</span> _localVar <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>
            _delObj <span style="color: #008000;">+=</span> <span style="color: #FF0000;">delegate</span><span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> _inpar<span style="color: #000000;">&#41;</span>
            <span style="color: #000000;">&#123;</span>
                _localVar<span style="color: #008000;">++;</span>
                Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Anonymous method says: &quot;</span><span style="color: #008000;">+</span>_inpar<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #000000;">&#125;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #008080; font-style: italic;">//Before invoking the delegate the value is 0</span>
            Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Local Variable : &quot;</span> <span style="color: #008000;">+</span> _localVar<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #008080; font-style: italic;">//Lets invoke the delegate</span>
            _delObj.<span style="color: #0000FF;">Invoke</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Hello World&quot;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #008080; font-style: italic;">//After invoking, the value becomes 1</span>
            Console.<span style="color: #0000FF;">WriteLine</span><span style="color: #000000;">&#40;</span><span style="color: #666666;">&quot;Local Variable : &quot;</span> <span style="color: #008000;">+</span> _localVar<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span></pre></td></tr></table></div>

<p style="text-align: justify;">Behind the screens the compilers does a lot of work to get captured variables work. In the MSIL, there is no sign of the local variable, instead a reference variable is created which has the local integer as a member and all modifications are done to it.</p>
<p><a href="http://blog.ganeshzone.net/blog/wp-content/uploads/2009/12/capturedVariables.jpg"><img class="aligncenter size-medium wp-image-685" title="capturedVariables" src="http://blog.ganeshzone.net/blog/wp-content/uploads/2009/12/capturedVariables-300x138.jpg" alt="" width="300" height="138" /></a></p>
<p style="text-align: justify;">The IL shows the int declaration has disappeared in the TestDelegates method. Instead an instance of the class c_Displayclass1 is created and used. The local variable is a member of this instance class and this is the variable that is incremented both in the TestDelegates method as well as the invocation giving the illusion of usage of the local variable in the anonymous method body scope. For short declarations and one or two variables this feature would be quite useful, but a large number of captured variables would make the code difficult to understand, hence compromising the biggest advantage of anonymous methods</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
</pre></td><td class="code"><pre class="cil" style="font-family:monospace;"><span style="color:maroon;font-weight:bold;">.method</span> <span style="color:blue;font-weight:bold;">public</span> <span style="color:blue;font-weight:bold;">hidebysig</span> <span style="color:blue;font-weight:bold;">static</span> <span style="color:purple;font-weight:bold;">void</span>  TestDelegates<span style="color: #006400;">&#40;</span><span style="color: #006400;">&#41;</span> <span style="color:blue;font-weight:bold;">cil</span> <span style="color:blue;font-weight:bold;">managed</span>
<span style="color: #006400;">&#123;</span>
   <span style="color:maroon;font-weight:bold;">.locals</span> <span style="color:blue;font-weight:bold;">init</span> <span style="color: #006400;">&#40;</span><span style="color: #006400;">&#91;</span><span style="color: #00008B;">0</span><span style="color: #006400;">&#93;</span> <span style="color:blue;font-weight:bold;">class</span> AnonyMeth.TestClass/writeToScreen _delObj,
           <span style="color: #006400;">&#91;</span><span style="color: #00008B;">1</span><span style="color: #006400;">&#93;</span> <span style="color:blue;font-weight:bold;">class</span> AnonyMeth.TestClass/'&amp;lt;&amp;gt;c__DisplayClass1' 'CS$&amp;lt;&amp;gt;<span style="color: #00008B;">8</span>__locals2'<span style="color: #006400;">&#41;</span>
  IL_0000:  <span style="color:blue;">newobj</span>     <span style="color:blue;font-weight:bold;">instance</span> <span style="color:purple;font-weight:bold;">void</span> AnonyMeth.TestClass/'&amp;lt;&amp;gt;c__DisplayClass1'::<span style="color:maroon;font-weight:bold;">.ctor</span><span style="color: #006400;">&#40;</span><span style="color: #006400;">&#41;</span>
  IL_0005:  <span style="color:blue;">stloc</span>.<span style="color:blue;">1</span>
 <span style="color:gray;font-style:italic;">//removed for brevity</span>
  IL_0019:  <span style="color:blue;">stfld</span>      <span style="color:purple;font-weight:bold;">int32</span> AnonyMeth.TestClass/'&amp;lt;&amp;gt;c__DisplayClass1'::_localVar
  IL_001e:  <span style="color:blue;">ldloc</span>.<span style="color:blue;">0</span>
  IL_001f:  <span style="color:blue;">ldloc</span>.<span style="color:blue;">1</span>
  IL_0020:  <span style="color:blue;">ldftn</span>      <span style="color:blue;font-weight:bold;">instance</span> <span style="color:purple;font-weight:bold;">void</span> AnonyMeth.TestClass/'&amp;lt;&amp;gt;c__DisplayClass1'::'b__0'<span style="color: #006400;">&#40;</span><span style="color:purple;font-weight:bold;">string</span><span style="color: #006400;">&#41;</span>
  IL_0026:  <span style="color:blue;">newobj</span>     <span style="color:blue;font-weight:bold;">instance</span> <span style="color:purple;font-weight:bold;">void</span> AnonyMeth.TestClass/writeToScreen::<span style="color:maroon;font-weight:bold;">.ctor</span><span style="color: #006400;">&#40;</span><span style="color:purple;font-weight:bold;">object</span>,
                                                                              <span style="color:blue;font-weight:bold;">native</span> <span style="color:purple;font-weight:bold;">int</span><span style="color: #006400;">&#41;</span>
  IL_002b:  <span style="color:blue;">call</span>       <span style="color:blue;font-weight:bold;">class</span> <span style="color: #006400;">&#91;</span>mscorlib<span style="color: #006400;">&#93;</span>System.Delegate <span style="color: #006400;">&#91;</span>mscorlib<span style="color: #006400;">&#93;</span>System.Delegate::<span style="color: #000033;">Combine</span><span style="color: #006400;">&#40;</span><span style="color:blue;font-weight:bold;">class</span> <span style="color: #006400;">&#91;</span>mscorlib<span style="color: #006400;">&#93;</span>System.Delegate,
                                                                                          <span style="color:blue;font-weight:bold;">class</span> <span style="color: #006400;">&#91;</span>mscorlib<span style="color: #006400;">&#93;</span>System.Delegate<span style="color: #006400;">&#41;</span>
  IL_0030:  <span style="color:blue;">castclass</span>  AnonyMeth.TestClass/writeToScreen
  IL_0035:  <span style="color:blue;">stloc</span>.<span style="color:blue;">0</span>
  IL_0036:  <span style="color:blue;">ldstr</span>      <span style="color: #008000;">&quot;Local Variable : &quot;</span>
  IL_003b:  <span style="color:blue;">ldloc</span>.<span style="color:blue;">1</span>
  IL_003c:  <span style="color:blue;">ldfld</span>      <span style="color:purple;font-weight:bold;">int32</span> AnonyMeth.TestClass/'&amp;lt;&amp;gt;c__DisplayClass1'::_localVar
  <span style="color:gray;font-style:italic;">//The instance variable of c__displayclass1 is displayed here</span>
  <span style="color:gray;font-style:italic;">//removed for brevity</span>
  IL_0075:  <span style="color:blue;">ret</span>
<span style="color: #006400;">&#125;</span> <span style="color:gray;font-style:italic;">// end of method TestClass::TestDelegates</span></pre></td></tr></table></div>

]]></content:encoded>
			<wfw:commentRss>http://blog.ganeshzone.net/blog/index.php/2009/12/anonymous-methods-and-captured-variables-in-c-2-0/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
