<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="http://blogs.msdn.com/utility/FeedStylesheets/rss.xsl" media="screen"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:wfw="http://wellformedweb.org/CommentAPI/"><channel><title>jaredpar's WebLog : Closures</title><link>http://blogs.msdn.com/jaredpar/archive/tags/Closures/default.aspx</link><description>Tags: Closures</description><dc:language>en-US</dc:language><generator>CommunityServer 2.1 SP1 (Build: 61025.2)</generator><item><title>Why is LINQ absent from debugger windows?</title><link>http://blogs.msdn.com/jaredpar/archive/2009/08/26/why-no-linq-in-debugger-windows.aspx</link><pubDate>Wed, 26 Aug 2009 15:00:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9877055</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>9</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/9877055.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=9877055</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=9877055</wfw:comment><description>&lt;p&gt;As the owner of the VB.Net portion of the overall debugging experience, I frequently hear the request from customers to add LINQ support into the Watch / Immediate and Locals window.&amp;nbsp; Virtually every other type of expression is available in the debugger windows so why leave one of the most popular ones out? &lt;/p&gt;  &lt;p&gt;Quick Diversion: the specifics of this article are written from the point of view of the VB.Net expression evaluator.&amp;nbsp; However, the limitations blocking LINQ support (in both the architecture and overall design) are very similar between VB.Net and C#.&amp;nbsp; &lt;/p&gt;  &lt;p&gt;As usual, the primary issue is cost and the cost for LINQ in the debugger windows is very high.&amp;nbsp; To understand why the cost is so high though, we must start by getting a better understanding how a language service interacts with the debugging services of Visual Studio and the general philosophy around compiler features in the debugger.&amp;nbsp; &lt;/p&gt;  &lt;p&gt;Languages in Visual Studio typically provide the following major components to support the debugging experience.&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;     &lt;p&gt;Expression Evaluator (EE): This is the language specific component which provides all of the data used in the watch, locals and immediate window, data tips, conditional breakpoints and several other components.&amp;nbsp; It’s primary input is an expression in string form which is converted to a value (typically an ICorDebugValue instance) and outputs a COM object capable of inspecting that value to the core debugger [1].&amp;nbsp;&amp;nbsp; Everything typed into the debugger windows goes through the EE.&lt;/p&gt;      &lt;p&gt;This component lives in the MTA of Visual Studio and has almost no interaction with the UI / STA thread. &lt;/p&gt;   &lt;/li&gt;    &lt;li&gt;     &lt;p&gt;ENC Service: This is the component which is the work horse of ENC operations.&amp;nbsp; It provides rude edit detection, metadata differencing and metadata + IL generation&amp;nbsp;&amp;nbsp; .&lt;/p&gt;      &lt;p&gt;This component lives in the main STA of Visual Studio&lt;/p&gt;   &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;The important thing to understand about the expression evaluator is that it’s purpose is primarily to provide an expression evaluation and data inspection service.&amp;nbsp; How expression evaluation works is an article in itself but suffice it to say that it converts the string to a very low level AST then walks the nodes bottom up and evaluating the expressions using the ICorDebug APIs.&amp;nbsp; The EE component has no UI and is simply a data provider for the core debugger services.&amp;nbsp;&amp;nbsp; &lt;/p&gt;  &lt;p&gt;The design philosophy for Both VB.Net and C# is to have the highest level of fidelity between expressions evaluated in the EE and the actual running program.&amp;nbsp; To do otherwise would lead to extremely confusing results for users.&amp;nbsp; When spec’ing feature support in the VB.Net EE we start from the point of 100% fidelity, determine the problems with this design (if any) and then start the difficult process of making compromises.&amp;nbsp; &lt;/p&gt;  &lt;p&gt;LINQ expressions are very different than any other expression previously allowed in the EE window because of the features interaction with metadata.&amp;nbsp; All LINQ expressions require the generation or manipulation of metadata to support the underlying lambda and/or closure.&amp;nbsp; Adding support for this is one of the biggest hurdles to getting LINQ (and other features) into the EE.&amp;nbsp;&amp;nbsp; &lt;/p&gt;  &lt;p&gt;Evaluating a LINQ expression is actually much closer to an ENC operation than a traditional EE one.&amp;nbsp; &lt;/p&gt;  &lt;p&gt;Currently the EE’s have no capacity for generating metadata, only interpreting it.&amp;nbsp; Operations which mutate or generate metadata have traditionally only been allowed via the ENC service.&amp;nbsp; Getting LINQ to work in the EE with true fidelity would require at least a minimal amount of ENC feature work.&amp;nbsp; &lt;/p&gt;  &lt;p&gt;Without getting into too much detail, lets enumerate the&lt;b&gt; new&lt;/b&gt; major features necessary to evaluate a LINQ expression in the EE with true fidelity to the running program.&amp;nbsp; To simplify things, we’ll start by assuming there is no other LINQ expression used in the current method and the method is only being executed at most once at any given time in the process.&amp;nbsp;&amp;nbsp; &lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;A metadata generation service to support the backing for closures and lambda expressions &lt;/li&gt;    &lt;li&gt;Convert expressions typed in the EE into IL [2] &lt;/li&gt;    &lt;li&gt;ENC support for metadata to push the new metadata for closures and lambdas into the currently executing assembly &lt;/li&gt;    &lt;li&gt;ENC support for method body IL to remove lifted variables from the current method and redirect the references inside the closure&lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;Issues #1 and #2 are for the most part internal architecture issues and can be solved via normal processes of code base refactoring and adding new features to an existing component.&amp;nbsp;&amp;nbsp; I don’t mean to imply these problems are cheap (in fact they are relatively expensive)&amp;nbsp; But fixing these is somewhat of an understood quantity.&amp;nbsp; &lt;/p&gt;  &lt;p&gt;Issues #3 and #4 are where the problems start.&amp;nbsp; As implemented EE’s do not have capability to create or modify metadata in the running process (that is the job of the ENC service).&amp;nbsp; EE’s do have access to the underlying CLR ENC APIs so it is possible to implement ENC operations in the EE.&amp;nbsp; It’s just simply not been done yet.&amp;nbsp; &lt;/p&gt;  &lt;p&gt;Wait!&amp;nbsp; Why not reuse our ENC implementation in the EE?&amp;nbsp; Unfortunately the ENC service is currently tied heavily to our in memory IDE compiler and many other IDE / STA features.&amp;nbsp; It in fact lives in a completely separate DLL, separate COM apartment and works on a different symbol table than the EE.&amp;nbsp; &lt;/p&gt;  &lt;p&gt;More fundamental though is that it’s designed for a completely different purpose.&amp;nbsp; ENC is designed to track edits in live code, determining the differences and applying them to the running program.&amp;nbsp; The hypothetical EE feature would be tracking expressions that modify a running DLL for which code is not guaranteed (and not likely) to be available and applying the difference to the running program.&amp;nbsp; There are some similarities but the differences are significant enough to make code reuse have limited value.&amp;nbsp; &lt;/p&gt;  &lt;p&gt;Some people may wonder why it’s necessary to implement #4.&amp;nbsp; Couldn’t we just avoid removing the variable from the current method and make the feature cheaper?&amp;nbsp; This is possible but it would cause a significant fidelity difference in the feature.&amp;nbsp; Any mutations of the local variable within the LINQ expression would not be visible on the stack frame as it would if the LINQ expression was present in the original program.&amp;nbsp; &lt;/p&gt;  &lt;p&gt;It’s easy to think of this ENC in the EE as just the same type of cost as #1 and #2 (in many ways it is).&amp;nbsp; However taking advantage of the CLR ENC APIs in the EE also means that we inherit it’s limitations as well.&amp;nbsp; ENC as as implemented in the CLR has many limitations which fly in the face of LINQ.&amp;nbsp; In particular the following ENC limitations present major problems (&lt;a mce_href="http://blogs.msdn.com/jmstall/archive/2005/02/19/376666.aspx" href="http://blogs.msdn.com/jmstall/archive/2005/02/19/376666.aspx"&gt;ENC limitations reference&lt;/a&gt;).&amp;nbsp; &lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;Cannot add members to a value type.&amp;nbsp; This prevents evaluating LINQ when stopped in a value type method &lt;/li&gt;    &lt;li&gt;Cannot remove locals from a function.&amp;nbsp; This is an implementation of LINQ but we could work around this problem by changing the IL to simply no longer accessing the local variables. &lt;/li&gt;    &lt;li&gt;Cannot change anything in a generic type.&amp;nbsp; This prevents evaluating LINQ when stopped in a generic type.&amp;nbsp; &lt;/li&gt;    &lt;li&gt;Cannot specify an initial value for newly added fields. &lt;/li&gt;    &lt;li&gt;Allowable ENC operations differ between the top of the stack and operations elsewhere within the stack &lt;/li&gt;    &lt;li&gt;Modification of a non-top stack frame cannot significantly edit the current function call.&amp;nbsp; So if a LINQ expression captures a variable used in that call (think ref passing) it would likely be unable to be evaluated.&lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;So even if we implemented everything possible on the language service side the resulting feature would be limited in several impactful ways.&amp;nbsp; Additionally these limitations are somewhat orthogonal to the current limitations EE’s face and would require a bit of user education.&amp;nbsp; And this is only for the most basic LINQ feature under unrealistic scenarios.&amp;nbsp; &lt;/p&gt;  &lt;p&gt;Lets now consider the problems of evaluating a LINQ expression when the current method already contains a LINQ expression that lifts at least 1 variable.&amp;nbsp; Evaluating a new expression at the same scope would require the modification of the current closure to maintain fidelity as opposed to generating a new one.&amp;nbsp; This brings along with it a couple more problems.&amp;nbsp; &lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;     &lt;p&gt;A lambda expression which uses 2 variables, 1 of which is captured in an existing lambda expression.&amp;nbsp; To maintain fidelity we would have to modify an existing closure signature to contain the new variable. &lt;/p&gt;      &lt;p&gt;&amp;nbsp;&lt;/p&gt;      &lt;p&gt;Often times generated closures are generic so we would run straight into ENC limitation #3. Additionally we would need the newly added field to have the same value as it has in the current method which runs us into ENC limitation #4. Now also consider that a closure instance can live much longer than the method in which it was created. For those closures no stack value is available so what value should we give fields in that instance?&amp;nbsp; Ideally it should have the value of the variable at the point the method exited but realistically that’s not possible.&amp;nbsp; &lt;/p&gt;      &lt;p&gt;&amp;nbsp;&lt;/p&gt;   &lt;/li&gt;    &lt;li&gt;     &lt;p&gt;A lambda expression which uses 1 variable in a method where an existing lambda expression captures that same variable and another.&amp;nbsp; To maintain fidelity we would have to know about this and fake capture the second variable as well.&lt;/p&gt;   &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;Now consider all of the problems above and consider the scenario where there are multiple threads and multiple instances of the current method active in the program.&amp;nbsp; How to determine which closure instance belongs to which thread, and just as important which stack frame on which thread, with respect to initializing values?&lt;/p&gt;  &lt;p&gt;None of the issues are an unsolvable problem but they do represent a significant cost to the feature.&amp;nbsp; And once again even if we added all of these features to the EE, ENC limitations would significantly limit the usefulness of the resulting feature.&amp;nbsp; &lt;/p&gt;  &lt;p&gt;Does this mean that LINQ, or any future metadata requiring expression, will never be added to the debugger window?&amp;nbsp; Absolutely not.&amp;nbsp; We’ve just hit the difficult stage of making compromises on the level of fidelity in the feature.&amp;nbsp; If you back off of true fidelity in a few small ways the resulting feature, while still very expensive, is significantly cheaper and removes many of the limitations imposed by ENC.&amp;nbsp;&amp;nbsp; This &lt;b&gt;hypothetical&lt;/b&gt; feature will be discussed in my next article.&amp;nbsp; &lt;/p&gt;  &lt;p&gt;[1] For those interested the returned interface is &lt;a mce_href="http://msdn.microsoft.com/en-us/library/bb161287(VS.80).aspx" href="http://msdn.microsoft.com/en-us/library/bb161287(VS.80).aspx"&gt;IDebugProperty2&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;[2] Right now expressions are converted to a tree form slightly above IL and they are interpreted using the ICorDebug APIs.&amp;nbsp; Converting all the way down to IL requires a lot more work&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9877055" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/VB/default.aspx">VB</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Closures/default.aspx">Closures</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Debugging/default.aspx">Debugging</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Lambda/default.aspx">Lambda</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/LINQ/default.aspx">LINQ</category></item><item><title>Script Blocks and Closures (or lack there of)</title><link>http://blogs.msdn.com/jaredpar/archive/2009/01/08/script-blocks-and-closures-or-lack-there-of.aspx</link><pubDate>Thu, 08 Jan 2009 16:00:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9243382</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>0</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/9243382.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=9243382</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=9243382</wfw:comment><description>&lt;p&gt;Script blocks are a concise way of representing an expression or statement group in Powershell.&amp;#160; It’s the C#/F#/VB lambda equivalent for PowerShell.&amp;#160; &lt;/p&gt;  &lt;p&gt;One difference between C#/F#/VB lambda expressions and a scriptblock is the lack of lexical closures (otherwise known as variable capturing).&amp;#160; This feature allows for a variable defined in an outer scope to be captured by the lambda in such a way that the value is maintained with the lambda expression.&amp;#160; The details on how the variable is captured can vary from language to language but the basics are the same.&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;static void &lt;/span&gt;ClosureExample() {
    &lt;span style="color: blue"&gt;var &lt;/span&gt;name = &lt;span style="color: #a31515"&gt;&amp;quot;first&amp;quot;&lt;/span&gt;;
    &lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt; captureName = () =&amp;gt; name;
    name = &lt;span style="color: #a31515"&gt;&amp;quot;second&amp;quot;&lt;/span&gt;;
    &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(captureName());   &lt;span style="color: green"&gt;// prints: second
&lt;/span&gt;}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Due to the flexible nature of powershell it is possible for a scriptblock to appear to have captured a variable when in fact it’s just a quirk of variable name resolution.&amp;#160; An important item to remember when considering how a scriptblock will execute is knowing that a script block is evaluated at the point of execution, not the point of definition.&amp;#160;&amp;#160; &lt;/p&gt;

&lt;pre&gt;PS) function example1() { $b = 42; { $b } }
PS) $b = 42
PS) $sb = example1
PS) &amp;amp; $sb
42&lt;/pre&gt;

&lt;p&gt;The above sample works because when $sb is evaluated there is a variable $b in scope and hence the expression binds to that value.&amp;#160; Not the original one in “example1”.&amp;#160; &lt;/p&gt;

&lt;p&gt;This is a somewhat contrived example.&amp;#160; But the problem can easily occur when scripts 1) contain the same variable name in multiple scopes/contexts, 2) uses one of those variables within a script block.&amp;#160; I’ve run into this problem myself several times.&amp;#160; &lt;/p&gt;

&lt;p&gt;Here is a more complex sample that demonstrates the timing of the name resolution.&lt;/p&gt;

&lt;pre&gt;PS) function example2() { param ($p1) $v1 = &amp;quot;avalue&amp;quot;; &amp;amp; $p1 }
PS) example2 {$doesnotexist}
PS) example2 {$v1}
avalue&lt;/pre&gt;

&lt;p&gt;This behavior though can also be used as a feature.&amp;#160; Part of the implicit contract of a scriptblock can be the existance of certain named variables in the scope where the script block is executed.&amp;#160; Probably not the best code maintainability practice, but I think we can generate a few good samples in a future post.&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9243382" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/PowerShell/default.aspx">PowerShell</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Closures/default.aspx">Closures</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Lambda/default.aspx">Lambda</category></item><item><title>Closures in VB Part 6: Limitations</title><link>http://blogs.msdn.com/jaredpar/archive/2007/08/06/closures-in-vb-part-6-limitations.aspx</link><pubDate>Tue, 07 Aug 2007 01:36:40 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:4267111</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>0</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/4267111.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=4267111</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=4267111</wfw:comment><description>&lt;p&gt;For previous articles in this series please see ...&lt;/p&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="http://blogs.msdn.com/jaredpar/archive/2007/04/27/closures-in-vb-part-1.aspx"&gt;Part 1: Introduction&lt;/a&gt;  &lt;li&gt;&lt;a href="http://blogs.msdn.com/jaredpar/archive/2007/05/03/closures-in-vb-part-2-method-calls.aspx"&gt;Part 2: Method Calls&lt;/a&gt;  &lt;li&gt;&lt;a href="http://blogs.msdn.com/jaredpar/archive/2007/05/25/closures-in-vb-part-3-scope.aspx"&gt;Part 3: Scope&lt;/a&gt;  &lt;li&gt;&lt;a href="http://blogs.msdn.com/jaredpar/archive/2007/06/15/closures-in-vb-part-4-variable-lifetime.aspx"&gt;Part 4: Variable Lifetime&lt;/a&gt;  &lt;li&gt;&lt;a href="http://blogs.msdn.com/jaredpar/archive/2007/07/26/closures-in-vb-part-5-looping.aspx"&gt;Part 5: Looping&lt;/a&gt;&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;As powerful as closures are in the language they do have a few limitations.&amp;nbsp; We worked hard in Orcas to put as few limitations in Orcas as possible.&amp;nbsp; Below are the current limitations and some insight into why they exist this way.&amp;nbsp; &lt;/p&gt; &lt;p&gt;1. Cannot use "ByRef" parameters in a closure&lt;/p&gt; &lt;p&gt;Example:&lt;/p&gt;&lt;pre&gt;    &lt;span style="color: blue"&gt;Sub&lt;/span&gt; LiftAByRef(&lt;span style="color: blue"&gt;ByRef&lt;/span&gt; x &lt;span style="color: blue"&gt;As&lt;/span&gt; &lt;span style="color: blue"&gt;Integer&lt;/span&gt;)
        &lt;span style="color: blue"&gt;Dim&lt;/span&gt; f = &lt;span style="color: blue"&gt;Function&lt;/span&gt;() x
    &lt;span style="color: blue"&gt;End&lt;/span&gt; &lt;span style="color: blue"&gt;Sub&lt;/span&gt;&lt;/pre&gt;
&lt;p&gt;Message: error BC36639: 'ByRef' parameter 'x' cannot be used in a lambda expression.&lt;/p&gt;
&lt;p&gt;The problem here is the expectation surrounding x.&amp;nbsp; Any change in the value of "x" inside the method "LiftAByRef" should be reflected in the calling function.&amp;nbsp;&amp;nbsp; Normally for any lifted parameter we add a new field inside the closure and all read/writes are redirected into that value.&amp;nbsp; For "ByRef" parameters we would additionally have to ensure that all writes are make to the parameter.&amp;nbsp; Even in the presence of an exception.&amp;nbsp; Not a trivial task.&amp;nbsp; &lt;/p&gt;
&lt;p&gt;2. Cannot use "Me" in a closure created inside a structure.&amp;nbsp; &lt;/p&gt;
&lt;p&gt;Example:&lt;/p&gt;&lt;pre&gt;&lt;span style="color: blue"&gt;Structure&lt;/span&gt; S1
    &lt;span style="color: blue"&gt;Public&lt;/span&gt; F1 &lt;span style="color: blue"&gt;As&lt;/span&gt; &lt;span style="color: blue"&gt;Integer&lt;/span&gt;

    &lt;span style="color: blue"&gt;Public&lt;/span&gt; &lt;span style="color: blue"&gt;Sub&lt;/span&gt; M1()
        &lt;span style="color: blue"&gt;Dim&lt;/span&gt; f = &lt;span style="color: blue"&gt;Function&lt;/span&gt;() F1
    &lt;span style="color: blue"&gt;End&lt;/span&gt; &lt;span style="color: blue"&gt;Sub&lt;/span&gt;
&lt;span style="color: blue"&gt;End&lt;/span&gt; &lt;span style="color: blue"&gt;Structure&lt;/span&gt;
&lt;/pre&gt;
&lt;p&gt;Message: error BC36638: Instance members and 'Me' cannot be used within a lambda expression in structures&lt;/p&gt;
&lt;p&gt;Closures capture values by reference.&amp;nbsp; It's not possible to capture the "Me" of a structure by reference in VB.&amp;nbsp; The only other option is to capture them by value.&amp;nbsp; If we did that then all changes to members of a structure inside a lambda would not affect the structure in which they were created; merely the value copy.&amp;nbsp; This is very different behavior from every other place that closures are used.&amp;nbsp; To avoid confusing behavior this is not a legal operation.&amp;nbsp; &lt;/p&gt;
&lt;p&gt;3. Cannot use a Restricted Type in a closure&lt;/p&gt;
&lt;p&gt;Example:&lt;/p&gt;&lt;pre&gt;    &lt;span style="color: blue"&gt;Sub&lt;/span&gt; LiftRestrictedType()
        &lt;span style="color: blue"&gt;Dim&lt;/span&gt; x &lt;span style="color: blue"&gt;As&lt;/span&gt; ArgIterator = &lt;span style="color: blue"&gt;Nothing&lt;/span&gt;
        &lt;span style="color: blue"&gt;Dim&lt;/span&gt; f = &lt;span style="color: blue"&gt;Function&lt;/span&gt;() x.GetNextArgType().GetModuleHandle()
    &lt;span style="color: blue"&gt;End&lt;/span&gt; &lt;span style="color: blue"&gt;Sub&lt;/span&gt;
&lt;/pre&gt;
&lt;p&gt;Message: error BC36640: Instance of restricted type 'System.ArgIterator' cannot be used in a lambda expression.&lt;/p&gt;
&lt;p&gt;This hopefully will not affect many users.&amp;nbsp; There are several types in the CLR that are considered &lt;em&gt;restricted&lt;/em&gt; because they have special semantics.&amp;nbsp; Typically they are special cased by the CLR and as such we can't use them in a closure.&amp;nbsp; Several of these cannot be used in VB at all.&amp;nbsp; They are ...&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;System.TypedReference 
&lt;li&gt;System.ArgIterator 
&lt;li&gt;System.RuntimeArgumentHandle&lt;/li&gt;&lt;/ul&gt;
&lt;p&gt;4. Cannot Goto&amp;nbsp;into scope that contains a closure &lt;/p&gt;
&lt;p&gt;Example:&lt;/p&gt;&lt;pre&gt;    &lt;span style="color: blue"&gt;Sub&lt;/span&gt; BadGoto()
        &lt;span style="color: blue"&gt;Dim&lt;/span&gt; x = &lt;span style="color: maroon"&gt;0&lt;/span&gt;

        &lt;span style="color: blue"&gt;GoTo&lt;/span&gt; Label1
        &lt;span style="color: blue"&gt;If&lt;/span&gt; x &amp;gt; &lt;span style="color: maroon"&gt;5&lt;/span&gt; &lt;span style="color: blue"&gt;Then&lt;/span&gt;
Label1:
            &lt;span style="color: blue"&gt;Dim&lt;/span&gt; y = &lt;span style="color: maroon"&gt;5&lt;/span&gt;
            &lt;span style="color: blue"&gt;Dim&lt;/span&gt; f = &lt;span style="color: blue"&gt;Function&lt;/span&gt;() y
        &lt;span style="color: blue"&gt;End&lt;/span&gt; &lt;span style="color: blue"&gt;If&lt;/span&gt;
    &lt;span style="color: blue"&gt;End&lt;/span&gt; &lt;span style="color: blue"&gt;Sub&lt;/span&gt;&lt;/pre&gt;
&lt;p&gt;Message: error BC36597: 'GoTo Label1' is not valid because 'Label1' is inside a scope that defines a variable that is used in a lambda or query expression.&lt;/p&gt;
&lt;p&gt;If you look back at &lt;a href="http://blogs.msdn.com/jaredpar/archive/2007/05/25/closures-in-vb-part-3-scope.aspx"&gt;Part 3&lt;/a&gt;&amp;nbsp;of this series you will see that a lot of work goes into initializing closures inside of a scope.&amp;nbsp; Unfortunately allowing a user to jump into a block that contains a closure makes respecting these rules very difficult.&amp;nbsp; In a even trivial example in makes the resulting code mostly unreadable.&amp;nbsp; We decided to disable this in Orcas and reconsider it in a future release.&lt;/p&gt;
&lt;p&gt;It is perfectly legal however to jump into any scope that is currently visible regardless of whether or not in contains a closure.&amp;nbsp; Because jumping into a visible scope does not affect the creation of a variable lifetime (just the ending), it does not add any complications to the code.&amp;nbsp; &lt;/p&gt;
&lt;p&gt;5. Cannot mix "On Error Goto" and Closures&lt;/p&gt;
&lt;p&gt;Message: error BC36595: Method cannot contain both an 'On Error GoTo' statement and a lambda or query expression.&lt;/p&gt;
&lt;p&gt;Because of restriction #4 we must disable this scenario as well since it's very easy to hit this scenario with "On Error Goto".&amp;nbsp; &lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=4267111" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/VB/default.aspx">VB</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/DotNet/default.aspx">DotNet</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Orcas/default.aspx">Orcas</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Closures/default.aspx">Closures</category></item><item><title>Closures in VB Part 5: Looping</title><link>http://blogs.msdn.com/jaredpar/archive/2007/07/26/closures-in-vb-part-5-looping.aspx</link><pubDate>Thu, 26 Jul 2007 19:39:05 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:4068113</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>2</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/4068113.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=4068113</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=4068113</wfw:comment><description>&lt;p&gt;For previous articles in the series please see&lt;/p&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="http://blogs.msdn.com/jaredpar/archive/2007/04/27/closures-in-vb-part-1.aspx"&gt;Part 1: Introduction&lt;/a&gt;  &lt;li&gt;&lt;a href="http://blogs.msdn.com/jaredpar/archive/2007/05/03/closures-in-vb-part-2-method-calls.aspx"&gt;Part 2: Method Calls&lt;/a&gt;  &lt;li&gt;&lt;a href="http://blogs.msdn.com/jaredpar/archive/2007/05/25/closures-in-vb-part-3-scope.aspx"&gt;Part 3: Scope&lt;/a&gt;  &lt;li&gt;&lt;a href="http://blogs.msdn.com/jaredpar/archive/2007/06/15/closures-in-vb-part-4-variable-lifetime.aspx"&gt;Part 4: Variable Lifetime&lt;/a&gt;&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;Once again sorry for the long delay between posts.&amp;nbsp;&lt;/p&gt; &lt;p&gt;Looping structures can cause unintended consequences when used with Lambda expressions.&amp;nbsp; The problem occurs because lambda expressions do not execute when they are constructed but rather when they are invoked.&amp;nbsp; For example take the following code.&amp;nbsp; &lt;/p&gt;&lt;pre&gt;    &lt;span style="color: blue"&gt;Sub&lt;/span&gt; LoopExample1()
        &lt;span style="color: blue"&gt;Dim&lt;/span&gt; list &lt;span style="color: blue"&gt;As&lt;/span&gt; &lt;span style="color: blue"&gt;New&lt;/span&gt; List(Of Func(Of &lt;span style="color: blue"&gt;Integer&lt;/span&gt;))
        &lt;span style="color: blue"&gt;For&lt;/span&gt; i = &lt;span style="color: maroon"&gt;0&lt;/span&gt; &lt;span style="color: blue"&gt;To&lt;/span&gt; &lt;span style="color: maroon"&gt;3&lt;/span&gt;
            list.Add(&lt;span style="color: blue"&gt;Function&lt;/span&gt;() i)
        &lt;span style="color: blue"&gt;Next&lt;/span&gt;

        &lt;span style="color: blue"&gt;For&lt;/span&gt; &lt;span style="color: blue"&gt;Each&lt;/span&gt; cur &lt;span style="color: blue"&gt;In&lt;/span&gt; list
            Console.Write(&lt;span style="color: maroon"&gt;"{0} "&lt;/span&gt;, cur())
        &lt;span style="color: blue"&gt;Next&lt;/span&gt;
    &lt;span style="color: blue"&gt;End&lt;/span&gt; &lt;span style="color: blue"&gt;Sub&lt;/span&gt;&lt;/pre&gt;
&lt;p&gt;Many users are surprised to find out the above will print "4 4 4 4 ".&amp;nbsp; The reason goes back to my previous 2 posts on variable lifetime and scope.&amp;nbsp; All "For" and "For Each" blocks in Vb have 2 scopes.&amp;nbsp; &lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Scope where iteration variables are defined 
&lt;li&gt;Body of the for loop&lt;/li&gt;&lt;/ol&gt;
&lt;p&gt;The first scope is entered only once no matter how many times the loop is executed.&amp;nbsp; The second is entered once per iteration of the loop.&amp;nbsp; Any iteration variables that are defined in a For/For Each loop are created in the first scope (in this case "i" and "cur").&amp;nbsp; Hence there is only one of those variables for every loop iteration and the lambda function lifts the single variable "i".&amp;nbsp; &lt;/p&gt;
&lt;p&gt;This has thrown off many users because the behavior works most of the time.&amp;nbsp; For instance if I switched the code to run "Console.Write" inside the first loop, it would print out&amp;nbsp;"0 1 2 3 "&amp;nbsp;as expected.&amp;nbsp; &lt;/p&gt;
&lt;p&gt;To mitigate against this problem the above code will actually produce a warning in VB.&amp;nbsp; &lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;warning BC42324: Using the iteration variable in a lambda expression may have unexpected results.&amp;nbsp; Instead, create a local variable within the loop and assign it the value of the iteration variable.&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;There are two ways to fix this problem depending on the behavior you want.&amp;nbsp; If you see this warning and don't know if it affects you, the safest change is to do the following.&amp;nbsp; &lt;/p&gt;&lt;pre&gt;    &lt;span style="color: blue"&gt;Sub&lt;/span&gt; LoopExample2()
        &lt;span style="color: blue"&gt;Dim&lt;/span&gt; list &lt;span style="color: blue"&gt;As&lt;/span&gt; &lt;span style="color: blue"&gt;New&lt;/span&gt; List(Of Func(Of &lt;span style="color: blue"&gt;Integer&lt;/span&gt;))
        &lt;span style="color: blue"&gt;For&lt;/span&gt; iTemp = &lt;span style="color: maroon"&gt;0&lt;/span&gt; &lt;span style="color: blue"&gt;To&lt;/span&gt; &lt;span style="color: maroon"&gt;3&lt;/span&gt;
            &lt;span style="color: blue"&gt;Dim&lt;/span&gt; i = iTemp
            list.Add(&lt;span style="color: blue"&gt;Function&lt;/span&gt;() i)
        &lt;span style="color: blue"&gt;Next&lt;/span&gt;

        &lt;span style="color: blue"&gt;For&lt;/span&gt; &lt;span style="color: blue"&gt;Each&lt;/span&gt; cur &lt;span style="color: blue"&gt;In&lt;/span&gt; list
            Console.Write(&lt;span style="color: maroon"&gt;"{0} "&lt;/span&gt;, cur())
        &lt;span style="color: blue"&gt;Next&lt;/span&gt;
    &lt;span style="color: blue"&gt;End&lt;/span&gt; &lt;span style="color: blue"&gt;Sub&lt;/span&gt;&lt;/pre&gt;
&lt;p&gt;This will cause "i" to be created in the second scope.&amp;nbsp; Hence there will be a different value for every loop iteration and the code will print out&amp;nbsp;"0 1 2 3"&amp;nbsp;as expected.&amp;nbsp; &lt;/p&gt;
&lt;p&gt;If you do want the code to print out "4 4 4 4 " then add "Dim i = 0" before the start of the loop.&amp;nbsp; &lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=4068113" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/VB/default.aspx">VB</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/DotNet/default.aspx">DotNet</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Orcas/default.aspx">Orcas</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Closures/default.aspx">Closures</category></item><item><title>Closures in VB Part 4: Variable Lifetime</title><link>http://blogs.msdn.com/jaredpar/archive/2007/06/15/closures-in-vb-part-4-variable-lifetime.aspx</link><pubDate>Fri, 15 Jun 2007 23:47:44 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:3319883</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>2</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/3319883.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=3319883</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=3319883</wfw:comment><description>&lt;p&gt;For previous articles in this series please see  &lt;ul&gt; &lt;li&gt;&lt;a href="http://blogs.msdn.com/jaredpar/archive/2007/04/27/closures-in-vb-part-1.aspx"&gt;Part 1: Introduction&lt;/a&gt;  &lt;li&gt;&lt;a href="http://blogs.msdn.com/jaredpar/archive/2007/05/03/closures-in-vb-part-2-method-calls.aspx"&gt;Part 2: Method Calls&lt;/a&gt;  &lt;li&gt;&lt;a href="http://blogs.msdn.com/jaredpar/archive/2007/05/25/closures-in-vb-part-3-scope.aspx"&gt;Part 3: Scope&lt;/a&gt;&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;Sorry for the long delay between posts here.&amp;nbsp; We're getting Orcas out the door and getting this series completed takes a back door to shipping.&amp;nbsp; &lt;/p&gt; &lt;p&gt;Originally I wanted to talk about looping structures next.&amp;nbsp; However when I started writing that post I realized that I had to talk about lifetime before the looping structures would make sense.&amp;nbsp; &lt;/p&gt; &lt;p&gt;Prior to Orcas the lifetime of a variable in VB was the entire function.&amp;nbsp; This presented several problems from a closures perspective.&amp;nbsp; Imagine you had a looping structure and the value was used in a lambda expression.&amp;nbsp; &lt;/p&gt;&lt;pre&gt;    &lt;span style="color: blue"&gt;Sub&lt;/span&gt; LifetimeExample()
        &lt;span style="color: blue"&gt;Dim&lt;/span&gt; list &lt;span style="color: blue"&gt;As&lt;/span&gt; &lt;span style="color: blue"&gt;New&lt;/span&gt; List(Of Func(Of &lt;span style="color: blue"&gt;Integer&lt;/span&gt;))
        &lt;span style="color: blue"&gt;For&lt;/span&gt; i = &lt;span style="color: maroon"&gt;0&lt;/span&gt; &lt;span style="color: blue"&gt;To&lt;/span&gt; &lt;span style="color: maroon"&gt;5&lt;/span&gt;

            &lt;span style="color: blue"&gt;Dim&lt;/span&gt; x = i * &lt;span style="color: maroon"&gt;2&lt;/span&gt;
            &lt;span style="color: blue"&gt;If&lt;/span&gt; &lt;span style="color: maroon"&gt;True&lt;/span&gt; &lt;span style="color: blue"&gt;Then&lt;/span&gt;
                list.Add(&lt;span style="color: blue"&gt;Function&lt;/span&gt;() x)
            &lt;span style="color: blue"&gt;End&lt;/span&gt; &lt;span style="color: blue"&gt;If&lt;/span&gt;
        &lt;span style="color: blue"&gt;Next&lt;/span&gt;

        &lt;span style="color: blue"&gt;For&lt;/span&gt; &lt;span style="color: blue"&gt;Each&lt;/span&gt; f &lt;span style="color: blue"&gt;In&lt;/span&gt; list
            Console.Write(f() &amp;amp; " ")
        &lt;span style="color: blue"&gt;Next&lt;/span&gt;
    &lt;span style="color: blue"&gt;End&lt;/span&gt; &lt;span style="color: blue"&gt;Sub&lt;/span&gt;&lt;/pre&gt;
&lt;p&gt;In this example if we left the lifetime rules unchanged, there would be a single variable "x" for the entire function.&amp;nbsp; That means that we would end up printing out &lt;/p&gt;
&lt;p&gt;10 10 10 10 10&lt;/p&gt;
&lt;p&gt;This is somewhat unexpected and essentially means that VB could not support complex Lambda scenarios.&amp;nbsp; To fix this we altered the lifetime of variables to be tied to the scope they were contained in.&amp;nbsp; The end effect is that each iteration of the loop has a separate "x" since each iteration enters and leaves the scope of the "if" statement.&amp;nbsp; As a result it will print out &lt;/p&gt;
&lt;p&gt;0 2 4 6 8 10&lt;/p&gt;
&lt;p&gt;We did make one backcompat adjustment for this change.&amp;nbsp; The lifetime of variables in VB was visible if you tried to use an uninitialized variable in a loop/goto.&amp;nbsp; For instance the following code will also print out 0 2 4 6 8 10 because it takes advantage of the fact that the variable "x" has a lifetime longer than the loop.&lt;/p&gt;&lt;pre&gt;    &lt;span style="color: blue"&gt;Sub&lt;/span&gt; VisibleLifetime()
        &lt;span style="color: blue"&gt;For&lt;/span&gt; i = &lt;span style="color: maroon"&gt;0&lt;/span&gt; &lt;span style="color: blue"&gt;To&lt;/span&gt; &lt;span style="color: maroon"&gt;5&lt;/span&gt;
            &lt;span style="color: blue"&gt;Dim&lt;/span&gt; x &lt;span style="color: blue"&gt;As&lt;/span&gt; &lt;span style="color: blue"&gt;Integer&lt;/span&gt;
            Console.WriteLine(x)
            x += &lt;span style="color: maroon"&gt;2&lt;/span&gt;
        &lt;span style="color: blue"&gt;Next&lt;/span&gt;
    &lt;span style="color: blue"&gt;End&lt;/span&gt; &lt;span style="color: blue"&gt;Sub&lt;/span&gt;&lt;/pre&gt;
&lt;p&gt;To make sure that we didn't break any existing code we had one little errata for the change.&amp;nbsp; When a variable's scope is re-entered, and hence recreated, and it is not initialized to a value it will get the last value of the variable.&amp;nbsp; &lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=3319883" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/VB/default.aspx">VB</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/DotNet/default.aspx">DotNet</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Orcas/default.aspx">Orcas</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Closures/default.aspx">Closures</category></item><item><title>Closures in VB Part 3: Scope</title><link>http://blogs.msdn.com/jaredpar/archive/2007/05/25/closures-in-vb-part-3-scope.aspx</link><pubDate>Fri, 25 May 2007 23:59:45 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:2880594</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>3</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/2880594.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=2880594</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=2880594</wfw:comment><description>&lt;p&gt;For previous articles in this series please see&lt;/p&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="http://blogs.msdn.com/jaredpar/archive/2007/04/27/closures-in-vb-part-1.aspx"&gt;Part 1: Introduction&lt;/a&gt;  &lt;li&gt;&lt;a href="http://blogs.msdn.com/jaredpar/archive/2007/05/03/closures-in-vb-part-2-method-calls.aspx"&gt;Part 2: Method Calls&lt;/a&gt;&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;Thus far in the series we've only lifted variables that are declared in the same block/scope.&amp;nbsp;What happens if we lift variables in different scope?&amp;nbsp; The answer is that one closure class will be created for every unique scope where a lifted variable is declared and all of the variables in that scope that are lifted will be placed in that closure.&amp;nbsp; Once again, examples speak best&lt;/p&gt;&lt;pre&gt;    &lt;span style="color: blue"&gt;Sub&lt;/span&gt; Scope1()
        &lt;span style="color: blue"&gt;Dim&lt;/span&gt; x = &lt;span style="color: maroon"&gt;5&lt;/span&gt;
        &lt;span style="color: blue"&gt;Dim&lt;/span&gt; f1 = &lt;span style="color: blue"&gt;Function&lt;/span&gt;(&lt;span style="color: blue"&gt;ByVal&lt;/span&gt; z &lt;span style="color: blue"&gt;As&lt;/span&gt; &lt;span style="color: blue"&gt;Integer&lt;/span&gt;) x + z
        Console.WriteLine(f1(&lt;span style="color: maroon"&gt;5&lt;/span&gt;))
        &lt;span style="color: blue"&gt;If&lt;/span&gt; x &amp;gt; &lt;span style="color: maroon"&gt;2&lt;/span&gt; &lt;span style="color: blue"&gt;Then&lt;/span&gt;
            &lt;span style="color: blue"&gt;Dim&lt;/span&gt; y = &lt;span style="color: maroon"&gt;6&lt;/span&gt;
            &lt;span style="color: blue"&gt;Dim&lt;/span&gt; g = &lt;span style="color: maroon"&gt;7&lt;/span&gt;
            &lt;span style="color: blue"&gt;Dim&lt;/span&gt; f2 = &lt;span style="color: blue"&gt;Function&lt;/span&gt;(&lt;span style="color: blue"&gt;ByVal&lt;/span&gt; z &lt;span style="color: blue"&gt;As&lt;/span&gt; &lt;span style="color: blue"&gt;Integer&lt;/span&gt;) z + y + g
            Console.WriteLine(f2(&lt;span style="color: maroon"&gt;4&lt;/span&gt;))
        &lt;span style="color: blue"&gt;End&lt;/span&gt; &lt;span style="color: blue"&gt;If&lt;/span&gt;
    &lt;span style="color: blue"&gt;End&lt;/span&gt; &lt;span style="color: blue"&gt;Sub&lt;/span&gt;&lt;/pre&gt;
&lt;p&gt;The code will end up looking like so ...&lt;/p&gt;&lt;pre&gt;    &lt;span style="color: blue"&gt;Class&lt;/span&gt; Closure1
        &lt;span style="color: blue"&gt;Public&lt;/span&gt; x &lt;span style="color: blue"&gt;As&lt;/span&gt; &lt;span style="color: blue"&gt;Integer&lt;/span&gt;

        &lt;span style="color: blue"&gt;Function&lt;/span&gt; Lambda_f1(&lt;span style="color: blue"&gt;ByVal&lt;/span&gt; z &lt;span style="color: blue"&gt;As&lt;/span&gt; &lt;span style="color: blue"&gt;Integer&lt;/span&gt;)
            &lt;span style="color: blue"&gt;Return&lt;/span&gt; x + z
        &lt;span style="color: blue"&gt;End&lt;/span&gt; &lt;span style="color: blue"&gt;Function&lt;/span&gt;

    &lt;span style="color: blue"&gt;End&lt;/span&gt; &lt;span style="color: blue"&gt;Class&lt;/span&gt;

    &lt;span style="color: blue"&gt;Class&lt;/span&gt; Closure2
        &lt;span style="color: blue"&gt;Public&lt;/span&gt; y &lt;span style="color: blue"&gt;As&lt;/span&gt; &lt;span style="color: blue"&gt;Integer&lt;/span&gt;
        &lt;span style="color: blue"&gt;Public&lt;/span&gt; g &lt;span style="color: blue"&gt;As&lt;/span&gt; &lt;span style="color: blue"&gt;Integer&lt;/span&gt;

        &lt;span style="color: blue"&gt;Function&lt;/span&gt; Lambda_f2(&lt;span style="color: blue"&gt;ByVal&lt;/span&gt; z &lt;span style="color: blue"&gt;As&lt;/span&gt; &lt;span style="color: blue"&gt;Integer&lt;/span&gt;)
            &lt;span style="color: blue"&gt;Return&lt;/span&gt; y + z + g
        &lt;span style="color: blue"&gt;End&lt;/span&gt; &lt;span style="color: blue"&gt;Function&lt;/span&gt;
    &lt;span style="color: blue"&gt;End&lt;/span&gt; &lt;span style="color: blue"&gt;Class&lt;/span&gt;

    &lt;span style="color: blue"&gt;Sub&lt;/span&gt; Scope1()
        &lt;span style="color: blue"&gt;Dim&lt;/span&gt; c1 &lt;span style="color: blue"&gt;As&lt;/span&gt; &lt;span style="color: blue"&gt;New&lt;/span&gt; Closure1()
        c1.x = &lt;span style="color: maroon"&gt;5&lt;/span&gt;
        Console.WriteLine(c1.Lambda_f1(&lt;span style="color: maroon"&gt;5&lt;/span&gt;))
        &lt;span style="color: blue"&gt;If&lt;/span&gt; c1.x &amp;gt; &lt;span style="color: maroon"&gt;2&lt;/span&gt; &lt;span style="color: blue"&gt;Then&lt;/span&gt;
            &lt;span style="color: blue"&gt;Dim&lt;/span&gt; c2 &lt;span style="color: blue"&gt;As&lt;/span&gt; &lt;span style="color: blue"&gt;New&lt;/span&gt; Closure2()
            c2.y = &lt;span style="color: maroon"&gt;6&lt;/span&gt;
            c2.g = &lt;span style="color: maroon"&gt;7&lt;/span&gt;
            Console.WriteLine(c2.Lambda_f2(&lt;span style="color: maroon"&gt;4&lt;/span&gt;))
        &lt;span style="color: blue"&gt;End&lt;/span&gt; &lt;span style="color: blue"&gt;If&lt;/span&gt;
    &lt;span style="color: blue"&gt;End&lt;/span&gt; &lt;span style="color: blue"&gt;Sub&lt;/span&gt;&lt;/pre&gt;
&lt;p&gt;There are a couple of items to take away from this example.&amp;nbsp; &lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Only two closure classes were created even though three variables were lifted.&amp;nbsp; The number of closures only depends on the number of scopes of all of the lifted declared variables. 
&lt;li&gt;The closures are created at the begining of the scope they are associated and not at the begining of the method.&amp;nbsp; This will be more important in the next part of the series.
&lt;li&gt;Each lambda instance is attached to the closure associated with the scope the lambda is declared in.&amp;nbsp; &lt;/li&gt;&lt;/ol&gt;
&lt;p&gt;The next&amp;nbsp;twist is what were to happen if&amp;nbsp;the lambda "f2" were to also use the variable "x".&amp;nbsp; As it's currently written there is no association between Closure1 and Closure2 therefore&amp;nbsp;there is no way for it to access the lifted variable.&amp;nbsp; The answer is two fold.&amp;nbsp;&amp;nbsp;Firstly to&amp;nbsp;reduce clutter I pasted the closure classes as if they were separate entries.&amp;nbsp; In fact Closure2 would appear as a nested class of Closure1 in the real generated code.&amp;nbsp; &lt;/p&gt;
&lt;p&gt;Secondly if x were used inside of "f2", the real use would be "c1.x".&amp;nbsp; That's (almost) no different than "someOtherVar.x".&amp;nbsp; Therefore the instance of c1 will be lifted into Closure2.&amp;nbsp; &lt;/p&gt;&lt;pre&gt;&lt;span style="color: blue"&gt;Dim&lt;/span&gt; f2 = &lt;span style="color: blue"&gt;Function&lt;/span&gt;(&lt;span style="color: blue"&gt;ByVal&lt;/span&gt; z &lt;span style="color: blue"&gt;As&lt;/span&gt; &lt;span style="color: blue"&gt;Integer&lt;/span&gt;) z + y + g + x&lt;/pre&gt;
&lt;p&gt;Woud result in the following definition of Closure2 ...&lt;/p&gt;&lt;pre&gt;    &lt;span style="color: blue"&gt;Class&lt;/span&gt; Closure2
        &lt;span style="color: blue"&gt;Public&lt;/span&gt; y &lt;span style="color: blue"&gt;As&lt;/span&gt; &lt;span style="color: blue"&gt;Integer&lt;/span&gt;
        &lt;span style="color: blue"&gt;Public&lt;/span&gt; g &lt;span style="color: blue"&gt;As&lt;/span&gt; &lt;span style="color: blue"&gt;Integer&lt;/span&gt;
        &lt;span style="color: blue"&gt;Public&lt;/span&gt; c1 &lt;span style="color: blue"&gt;As&lt;/span&gt; Closure1

        &lt;span style="color: blue"&gt;Function&lt;/span&gt; Lambda_f2(&lt;span style="color: blue"&gt;ByVal&lt;/span&gt; z &lt;span style="color: blue"&gt;As&lt;/span&gt; &lt;span style="color: blue"&gt;Integer&lt;/span&gt;)
            &lt;span style="color: blue"&gt;Return&lt;/span&gt; y + z + g + c1.x
        &lt;span style="color: blue"&gt;End&lt;/span&gt; &lt;span style="color: blue"&gt;Function&lt;/span&gt;
    &lt;span style="color: blue"&gt;End&lt;/span&gt; &lt;span style="color: blue"&gt;Class&lt;/span&gt;&lt;/pre&gt;
&lt;p&gt;In deeply nested lambdas and scopes this type of lifting will continue recursively.&amp;nbsp; &lt;/p&gt;
&lt;p&gt;That's it for this entry, the next article will talk about looping structures and possibly variable lifetime.&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=2880594" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/VB/default.aspx">VB</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/DotNet/default.aspx">DotNet</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Orcas/default.aspx">Orcas</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Closures/default.aspx">Closures</category></item><item><title>Closures in VB Part 2: Method Calls</title><link>http://blogs.msdn.com/jaredpar/archive/2007/05/03/closures-in-vb-part-2-method-calls.aspx</link><pubDate>Fri, 04 May 2007 00:56:51 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:2400211</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>9</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/2400211.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=2400211</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=2400211</wfw:comment><description>&lt;p&gt;For previous articles in this series, please see&lt;/p&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="http://blogs.msdn.com/jaredpar/archive/2007/04/27/closures-in-vb-part-1.aspx"&gt;Part 1 - The basics&lt;/a&gt;&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;This part of the series will focus on how method calls are handled in closures.&amp;nbsp;&amp;nbsp;As stated in the previous article, the purpose of closures is to allow all operations inside a lambda or query expression that would normally be available inside the function or sub.&amp;nbsp; To do this closures often need to capture (or lift) relevant variables from the function into the generated class.&lt;/p&gt; &lt;p&gt;There are&amp;nbsp;2 types of methods and method calls that closures have to handle.&amp;nbsp; &lt;/p&gt; &lt;ol&gt; &lt;li&gt;Method calls to a shared method or methods on modules.  &lt;li&gt;Method calls to instance members of a class &lt;/li&gt;&lt;/ol&gt; &lt;p&gt;&lt;strong&gt;Scenario #1 &lt;/strong&gt;&lt;/p&gt; &lt;p&gt;Below is an example of a method call inside a lambda expression for scenario #1.&amp;nbsp; &lt;/p&gt;&lt;pre&gt;&lt;span style="color: blue"&gt;Module&lt;/span&gt; M1

    &lt;span style="color: blue"&gt;Function&lt;/span&gt; MyValue() &lt;span style="color: blue"&gt;As&lt;/span&gt; &lt;span style="color: blue"&gt;Integer&lt;/span&gt;
        &lt;span style="color: blue"&gt;Return&lt;/span&gt; &lt;span style="color: maroon"&gt;42&lt;/span&gt;
    &lt;span style="color: blue"&gt;End&lt;/span&gt; &lt;span style="color: blue"&gt;Function&lt;/span&gt;

    &lt;span style="color: blue"&gt;Sub&lt;/span&gt; Example1()
        &lt;span style="color: blue"&gt;Dim&lt;/span&gt; x = &lt;span style="color: maroon"&gt;5&lt;/span&gt;
        &lt;span style="color: blue"&gt;Dim&lt;/span&gt; f = &lt;span style="color: blue"&gt;Function&lt;/span&gt;() x + MyValue()
    &lt;span style="color: blue"&gt;End&lt;/span&gt; &lt;span style="color: blue"&gt;Sub&lt;/span&gt;

&lt;span style="color: blue"&gt;End&lt;/span&gt; &lt;span style="color: blue"&gt;Module&lt;/span&gt;&lt;/pre&gt;
&lt;p&gt;Here we are calling a&amp;nbsp;module method inside a lambda.&amp;nbsp; Module Methods or Shared methods can be called from anywhere because they require no specific variable for the call.&amp;nbsp; This requires no special work from closures as the call can just be made naturally.&lt;/p&gt;&lt;pre&gt;    &lt;span style="color: blue"&gt;Class&lt;/span&gt; Closure
        &lt;span style="color: blue"&gt;Private&lt;/span&gt; x &lt;span style="color: blue"&gt;As&lt;/span&gt; &lt;span style="color: blue"&gt;Integer&lt;/span&gt;

        &lt;span style="color: blue"&gt;Function&lt;/span&gt; Lambda_f() &lt;span style="color: blue"&gt;As&lt;/span&gt; &lt;span style="color: blue"&gt;Integer&lt;/span&gt;
            &lt;span style="color: blue"&gt;Return&lt;/span&gt; x + M1.MyValue
        &lt;span style="color: blue"&gt;End&lt;/span&gt; &lt;span style="color: blue"&gt;Function&lt;/span&gt;
    &lt;span style="color: blue"&gt;End&lt;/span&gt; &lt;span style="color: blue"&gt;Class&lt;/span&gt;
&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;Scenario #2&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;Calling an instance method is more difficult than a shared method because it requires the referenc "Me".&amp;nbsp; If you don't type this specifically in code the VB Compiler will add it for you under the hood.&amp;nbsp; To make this work the closures code will also "lift" the variable "Me" in the same way that it lifts normal variables in a function.&amp;nbsp; &lt;/p&gt;
&lt;p&gt;Calling a instance method inside a lambda expression is little difference than calling a member method on a variable used in a lambda.&amp;nbsp; The only difference is the variable is "Me".&amp;nbsp; For example&lt;/p&gt;&lt;pre&gt;&lt;span style="color: blue"&gt;Class&lt;/span&gt; C1
    &lt;span style="color: blue"&gt;Private&lt;/span&gt; m_myValue &lt;span style="color: blue"&gt;As&lt;/span&gt; &lt;span style="color: blue"&gt;Integer&lt;/span&gt;

    &lt;span style="color: blue"&gt;Function&lt;/span&gt; MyValue() &lt;span style="color: blue"&gt;As&lt;/span&gt; &lt;span style="color: blue"&gt;Integer&lt;/span&gt;
        &lt;span style="color: blue"&gt;Return&lt;/span&gt; m_myValue
    &lt;span style="color: blue"&gt;End&lt;/span&gt; &lt;span style="color: blue"&gt;Function&lt;/span&gt;

    &lt;span style="color: blue"&gt;Sub&lt;/span&gt; Example2()
        &lt;span style="color: blue"&gt;Dim&lt;/span&gt; x = &lt;span style="color: maroon"&gt;5&lt;/span&gt;
        &lt;span style="color: blue"&gt;Dim&lt;/span&gt; f = &lt;span style="color: blue"&gt;Function&lt;/span&gt;() x + MyValue()
    &lt;span style="color: blue"&gt;End&lt;/span&gt; &lt;span style="color: blue"&gt;Sub&lt;/span&gt;
&lt;span style="color: blue"&gt;End&lt;/span&gt; &lt;span style="color: blue"&gt;Class&lt;/span&gt;&lt;/pre&gt;
&lt;p&gt;In this case we need to access both "x" and "Me.MyValue()" from the closure.&amp;nbsp; The generated code will create space for both of these variables and the transformed code in Example2 will store both of the values.&lt;/p&gt;&lt;pre&gt;&lt;span style="color: blue"&gt;Class&lt;/span&gt; Closure
    &lt;span style="color: blue"&gt;Private&lt;/span&gt; x &lt;span style="color: blue"&gt;As&lt;/span&gt; &lt;span style="color: blue"&gt;Integer&lt;/span&gt;
    &lt;span style="color: blue"&gt;Private&lt;/span&gt; OriginalMe &lt;span style="color: blue"&gt;As&lt;/span&gt; C1

    &lt;span style="color: blue"&gt;Function&lt;/span&gt; Lambda_f()
        &lt;span style="color: blue"&gt;Return&lt;/span&gt; x + OriginalMe.MyValue()
    &lt;span style="color: blue"&gt;End&lt;/span&gt; &lt;span style="color: blue"&gt;Function&lt;/span&gt;
&lt;span style="color: blue"&gt;End&lt;/span&gt; &lt;span style="color: blue"&gt;Class&lt;/span&gt;&lt;/pre&gt;&lt;pre&gt;    &lt;span style="color: blue"&gt;Sub&lt;/span&gt; Example2()
        &lt;span style="color: blue"&gt;Dim&lt;/span&gt; c &lt;span style="color: blue"&gt;As&lt;/span&gt; &lt;span style="color: blue"&gt;New&lt;/span&gt; Closure
        c.x = &lt;span style="color: maroon"&gt;5&lt;/span&gt;
        c.OriginalMe = &lt;span style="color: blue"&gt;Me&lt;/span&gt;
        &lt;span style="color: blue"&gt;Dim&lt;/span&gt; f = &lt;span style="color: blue"&gt;New&lt;/span&gt; Func(Of &lt;span style="color: blue"&gt;Integer&lt;/span&gt;)(&lt;span style="color: blue"&gt;AddressOf&lt;/span&gt; c.Lambda_f)
    &lt;span style="color: blue"&gt;End&lt;/span&gt; &lt;span style="color: blue"&gt;Sub&lt;/span&gt;&lt;/pre&gt;
&lt;p&gt;As usual, the generated code is much uglier but this essentially what will be generated.&amp;nbsp; That wraps it up for method calls.&amp;nbsp; In the next part, I will discuss the variable liftetime and scoping issues that come into play with closures.&amp;nbsp; &lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=2400211" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/VB/default.aspx">VB</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/DotNet/default.aspx">DotNet</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Orcas/default.aspx">Orcas</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Closures/default.aspx">Closures</category></item><item><title>Closures in VB: Part 1</title><link>http://blogs.msdn.com/jaredpar/archive/2007/04/27/closures-in-vb-part-1.aspx</link><pubDate>Sat, 28 Apr 2007 01:50:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:2304918</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>7</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/2304918.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=2304918</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=2304918</wfw:comment><description>&lt;P&gt;One of the features I implemented for VB 9.0 is lexical closure support.&amp;nbsp; This a great addition to the VB language and I wanted to do a series of blog posts to describe this feature and how it will impact your code.&lt;/P&gt;
&lt;P&gt;Lexical Closures (more often referred to as simply Closures) are the underpinnings for several new features in Visual Basic 9.0.&amp;nbsp; The are part of the guts of Lambda and Query expressions.&amp;nbsp; This will be a several part series on Closures in VB 9.0; how they work, their limitations, pitfalls surrounding their use.&amp;nbsp; &lt;/P&gt;
&lt;P&gt;To start off, let's get a basic summary of what a Closure is.&amp;nbsp; &lt;A href="http://en.wikipedia.org/wiki/Closure_%28computer_science%29" target=_blank mce_href="http://en.wikipedia.org/wiki/Closure_%28computer_science%29"&gt;Wikipedia&lt;/A&gt; defines it as "... a&amp;nbsp; is a semantic concept referring to a function paired with an environment ...".&amp;nbsp; I prefer to describe it as follows.&amp;nbsp; A closure is a feature which allows users to seemlessly access an environment (locals, parameters&amp;nbsp;and methods) from more than one function.&amp;nbsp; Even better are samples :) &lt;/P&gt;&lt;PRE&gt;    &lt;SPAN style="COLOR: blue"&gt;Class&lt;/SPAN&gt; C1
        &lt;SPAN style="COLOR: blue"&gt;Sub&lt;/SPAN&gt; Test()
            &lt;SPAN style="COLOR: blue"&gt;Dim&lt;/SPAN&gt; x = &lt;SPAN style="COLOR: maroon"&gt;5&lt;/SPAN&gt;
            &lt;SPAN style="COLOR: blue"&gt;Dim&lt;/SPAN&gt; f = &lt;SPAN style="COLOR: blue"&gt;Function&lt;/SPAN&gt;(&lt;SPAN style="COLOR: blue"&gt;ByVal&lt;/SPAN&gt; y &lt;SPAN style="COLOR: blue"&gt;As&lt;/SPAN&gt; &lt;SPAN style="COLOR: blue"&gt;Integer&lt;/SPAN&gt;) x + y
            &lt;SPAN style="COLOR: blue"&gt;Dim&lt;/SPAN&gt; result = f(&lt;SPAN style="COLOR: maroon"&gt;42&lt;/SPAN&gt;)
        &lt;SPAN style="COLOR: blue"&gt;End&lt;/SPAN&gt; &lt;SPAN style="COLOR: blue"&gt;Sub&lt;/SPAN&gt;

    &lt;SPAN style="COLOR: blue"&gt;End&lt;/SPAN&gt; &lt;SPAN style="COLOR: blue"&gt;Class&lt;/SPAN&gt;&lt;/PRE&gt;
&lt;P&gt;In this code we have a lambda expression which takes in a single parameter and adds it with a local variable.&amp;nbsp; Lambda expressions are implemented as functions in VB (and C#).&amp;nbsp; So now we have two functions, "Test" and "f", which are accessing a single local variable.&amp;nbsp; This is where closures come into play.&amp;nbsp; Closures are responsible for making the single variable "x" available to both functions in a process that is referred to as "lifting the variable".&lt;/P&gt;
&lt;P&gt;To do this the compiler will take essentially&amp;nbsp;4 actions.&amp;nbsp; &lt;/P&gt;
&lt;OL&gt;
&lt;LI&gt;Create a class which will contain "x" in order to share it among both functions.&amp;nbsp; Call it "Closure" for now 
&lt;LI&gt;It will create a new function for the lambda expression in the class "Closure".&amp;nbsp; Call it "f" for now 
&lt;LI&gt;Create a new instance of the class "Closure" inside the sub "Test" 
&lt;LI&gt;Rewrite all access of "x" into the member "x" of "Closure".&lt;/LI&gt;&lt;/OL&gt;&lt;PRE&gt;    &lt;SPAN style="COLOR: blue"&gt;Class&lt;/SPAN&gt; Closure
        &lt;SPAN style="COLOR: blue"&gt;Public&lt;/SPAN&gt; x &lt;SPAN style="COLOR: blue"&gt;As&lt;/SPAN&gt; &lt;SPAN style="COLOR: blue"&gt;Integer&lt;/SPAN&gt;

        &lt;SPAN style="COLOR: blue"&gt;Function&lt;/SPAN&gt; f(&lt;SPAN style="COLOR: blue"&gt;ByVal&lt;/SPAN&gt; y &lt;SPAN style="COLOR: blue"&gt;As&lt;/SPAN&gt; &lt;SPAN style="COLOR: blue"&gt;Integer&lt;/SPAN&gt;) &lt;SPAN style="COLOR: blue"&gt;As&lt;/SPAN&gt; &lt;SPAN style="COLOR: blue"&gt;Integer&lt;/SPAN&gt;
            &lt;SPAN style="COLOR: blue"&gt;Return&lt;/SPAN&gt; x + y
        &lt;SPAN style="COLOR: blue"&gt;End&lt;/SPAN&gt; &lt;SPAN style="COLOR: blue"&gt;Function&lt;/SPAN&gt;
    &lt;SPAN style="COLOR: blue"&gt;End&lt;/SPAN&gt; &lt;SPAN style="COLOR: blue"&gt;Class&lt;/SPAN&gt;

    &lt;SPAN style="COLOR: blue"&gt;Class&lt;/SPAN&gt; C1
        &lt;SPAN style="COLOR: blue"&gt;Sub&lt;/SPAN&gt; Test()
            &lt;SPAN style="COLOR: blue"&gt;Dim&lt;/SPAN&gt; c &lt;SPAN style="COLOR: blue"&gt;As&lt;/SPAN&gt; &lt;SPAN style="COLOR: blue"&gt;New&lt;/SPAN&gt; Closure()
            c.x = &lt;SPAN style="COLOR: maroon"&gt;5&lt;/SPAN&gt;
            &lt;SPAN style="COLOR: blue"&gt;Dim&lt;/SPAN&gt; f &lt;SPAN style="COLOR: blue"&gt;As&lt;/SPAN&gt; Func(Of &lt;SPAN style="COLOR: blue"&gt;Integer&lt;/SPAN&gt;, &lt;SPAN style="COLOR: blue"&gt;Integer&lt;/SPAN&gt;) = &lt;SPAN style="COLOR: blue"&gt;AddressOf&lt;/SPAN&gt; c.f
            &lt;SPAN style="COLOR: blue"&gt;Dim&lt;/SPAN&gt; result = f(&lt;SPAN style="COLOR: maroon"&gt;42&lt;/SPAN&gt;)
        &lt;SPAN style="COLOR: blue"&gt;End&lt;/SPAN&gt; &lt;SPAN style="COLOR: blue"&gt;Sub&lt;/SPAN&gt;

    &lt;SPAN style="COLOR: blue"&gt;End&lt;/SPAN&gt; &lt;SPAN style="COLOR: blue"&gt;Class&lt;/SPAN&gt;&lt;/PRE&gt;
&lt;P&gt;Now "x" is shared amongst both functions and the user didn't have to know anything about the code we generated.&amp;nbsp; You can see from this simplified example just how much code Closures and all of the other new VB 9.0 features are saving you here (Type Inference, Lambda Expressions).&amp;nbsp; &lt;/P&gt;
&lt;P&gt;Note this is only a simulation of what is generated when you use a closure, the actual generated code is much uglier and involves lots of unbindable names "$Lambda_1", etc ... &lt;/P&gt;
&lt;P&gt;In the next part of this article I'll dive into some more uses of closures (multiple variables, method access, &amp;nbsp;terminology, etc...).&lt;/P&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=2304918" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/VB/default.aspx">VB</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/DotNet/default.aspx">DotNet</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Orcas/default.aspx">Orcas</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Closures/default.aspx">Closures</category></item></channel></rss>