<?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 : VB</title><link>http://blogs.msdn.com/b/jaredpar/archive/tags/VB/</link><description>Tags: VB</description><dc:language>en-US</dc:language><generator>Telligent Community 5.6.583.21163 (Build: 5.6.583.21163)</generator><item><title>Interesting Late Binding Scenario with ToString</title><link>http://blogs.msdn.com/b/jaredpar/archive/2011/01/24/interesting-late-binding-scenario-with-tostring.aspx</link><pubDate>Mon, 24 Jan 2011 13:00:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10119290</guid><dc:creator>JaredPar MSFT</dc:creator><slash:comments>4</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/jaredpar/rsscomments.aspx?WeblogPostID=10119290</wfw:commentRss><comments>http://blogs.msdn.com/b/jaredpar/archive/2011/01/24/interesting-late-binding-scenario-with-tostring.aspx#comments</comments><description>&lt;p&gt;Not to long ago I received an email from a customer who wanted to report a bug in the VB.Net debugger.&amp;#160; They believed that there was a bug invoking ToString on Integer types in the immediate window and provided the following sample as evidence&lt;/p&gt;  &lt;pre class="code"&gt;i = 100
? i
100 {Integer}
    Integer: 100
? i.ToString(&amp;quot;c02&amp;quot;)
{&amp;quot;Conversion from string &amp;quot;c02&amp;quot; to type 'Integer' is not valid.&amp;quot;}
    _HResult: -2147467262
    _message: &amp;quot;Conversion from string &amp;quot;c02&amp;quot; to type 'Integer' is not valid.&amp;quot;
    Data: {System.Collections.ListDictionaryInternal}
    HelpLink: Nothing
    HResult: -2147467262
    InnerException: {&amp;quot;Input string was not in a correct format.&amp;quot;}
    IsTransient: False
    Message: &amp;quot;Conversion from string &amp;quot;c02&amp;quot; to type 'Integer' is not valid.&amp;quot;
    Source: &amp;quot;Microsoft.VisualBasic&amp;quot;
    StackTrace: &amp;quot;   at Microsoft.VisualBasic.CompilerServices.Conversions.ToInteger(String Value)&amp;quot;
    TargetSite: {Int32 ToInteger(System.String)}&lt;/pre&gt;

&lt;p&gt;The customer expected the method Integer.ToString(String) to be invoked and found the conversion to Integer to be a bug.&amp;#160; Surprisingly to the user, and several people on the team, this behavior is “By Design” [1].&amp;#160; To understand why we have to get a better picture of how exactly this is evaluated in the immediate window.&amp;#160; There are two particular areas of importance here.&amp;#160; &lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;The static type of the variable &lt;strong&gt;i &lt;/strong&gt;is Object not Integer.&amp;#160; The first expression “i = 1” declares a variable named &lt;strong&gt;i &lt;/strong&gt;in the context of the debugger and assigns it the value 100.&amp;#160; The ability to declare variables in the debugger predates type inference and uses Option Explicit Off semantics resulting in a type of Object for the variable&lt;/li&gt;

  &lt;li&gt;The debugger does not inherit project settings for Option Strict and instead evaluates all expressions with Option Strict Off.&amp;#160; &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;These two combine together to mean that almost every expression evaluated on a variable declared in the immediate window will be done in a late bound fashion.&amp;#160; It also means the above code sample is most accurately represented by the following real code.&lt;/p&gt;

&lt;pre class="code"&gt;    &lt;span style="color: blue"&gt;Sub &lt;/span&gt;Main()
        &lt;span style="color: blue"&gt;Dim &lt;/span&gt;i &lt;span style="color: blue"&gt;As Object &lt;/span&gt;= 100
        &lt;span style="color: blue"&gt;Dim &lt;/span&gt;result = i.ToString(&lt;span style="color: #a31515"&gt;&amp;quot;co2&amp;quot;&lt;/span&gt;)
    &lt;span style="color: blue"&gt;End Sub

&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;Compiling and running that code will indeed cause the exact same exception as viewed in the immediate window.&amp;#160; But why? &lt;/p&gt;

&lt;p&gt;Remember earlier I said that &lt;strong&gt;almost&lt;/strong&gt; every expression would be evaluated it a late bound fashion.&amp;#160; The compiler will use late binding when it can’t find a suitable method to bind to statically and late binding is otherwise allowed.&amp;#160; In this case the type of the variable is Object and hence Object.ToString() can be bound to statically and indeed that’s what happens in this case.&amp;#160; Further in VB.Net it’s possible to call a method that has no parameters without parens: ex i.ToString is legal.&amp;#160; This results in the (“c02”) portion of the expression being interpreted as an indexer expression into the resulting string.&amp;#160; Because Option Strict is off the compiler allows a silent narrowing conversion between String and Integer.&amp;#160; The result of all of this is the code is actually evaluated as &lt;/p&gt;

&lt;pre class="code"&gt;    &lt;span style="color: blue"&gt;Sub &lt;/span&gt;Main()
        &lt;span style="color: blue"&gt;Dim &lt;/span&gt;i &lt;span style="color: blue"&gt;As Object &lt;/span&gt;= 100
        &lt;span style="color: blue"&gt;Dim &lt;/span&gt;result = i.ToString()(&lt;span style="color: blue"&gt;CInt&lt;/span&gt;(&lt;span style="color: #a31515"&gt;&amp;quot;co2&amp;quot;&lt;/span&gt;))
    &lt;span style="color: blue"&gt;End Sub

&lt;/span&gt;&lt;/pre&gt;


&lt;p&gt;I certainly found this interesting the first time I encountered it. &lt;/p&gt;

&lt;p&gt;[1] Please don’t confuse me saying an issue is “By Design” with me thinking the behavior is ideal.&amp;#160; It’s merely a statement that the behavior conforms to the specification at the time of this writing. &lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10119290" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/jaredpar/archive/tags/VB/">VB</category><category domain="http://blogs.msdn.com/b/jaredpar/archive/tags/Debugging/">Debugging</category><category domain="http://blogs.msdn.com/b/jaredpar/archive/tags/Gotcha/">Gotcha</category></item><item><title>Why the debugging difference between C# and VB.Net return values?</title><link>http://blogs.msdn.com/b/jaredpar/archive/2011/01/12/why-the-debugging-difference-between-c-and-vb-net-return-values.aspx</link><pubDate>Wed, 12 Jan 2011 13:00:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10113852</guid><dc:creator>JaredPar MSFT</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/jaredpar/rsscomments.aspx?WeblogPostID=10113852</wfw:commentRss><comments>http://blogs.msdn.com/b/jaredpar/archive/2011/01/12/why-the-debugging-difference-between-c-and-vb-net-return-values.aspx#comments</comments><description>&lt;p&gt;A feature which seems to be getting more requests recently is support for seeing the return value of a function in the debugger without the need to assign it into a temporary.&amp;#160; C++’s had this feature for some time but it’s been lacking in managed debugging scenarios.&amp;#160; &lt;a href="http://blog.sublogic.com/"&gt;James Manning&lt;/a&gt; recently dedicated a couple of &lt;a href="http://blog.sublogic.com/2010/11/22/visual-studio-debugger-request-return-local-variable/"&gt;blog posts&lt;/a&gt; to the subject and &lt;a href="http://blog.sublogic.com/2010/12/11/showing-c-method-return-in-debugger-vb-net-can-do-it/"&gt;noted&lt;/a&gt; that the feature appears to already partially exist for VB.Net&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;“With VB.NET, the function name shows up as an entry in ‘Locals’ and the debugger shows us the value it’s returning!&amp;#160; The C# debugger has no such support, though – at the same ‘end of method’ breakpoint, only the parameter passed in is shown.&amp;#160;&amp;#160; So, clearly the CLR has enough support for the VB.NET debugger to support this feature, which would seem to be a pretty strong argument that the C# debugger certainly &lt;strong&gt;could&lt;/strong&gt; implement this feature.”&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Indeed C# could implement this feature but it’s not a CLR debugging feature that VB.Net is relying on but is rather an issue of VB6 legacy support.&amp;#160; The VB6 language didn’t have a return statement.&amp;#160; Instead values were returned by assigning the value to be returned to the name of the function.&amp;#160; For example&lt;/p&gt;  &lt;pre class="code"&gt;    &lt;span style="color: blue"&gt;Function &lt;/span&gt;IsEven(&lt;span style="color: blue"&gt;ByVal &lt;/span&gt;i &lt;span style="color: blue"&gt;As Integer&lt;/span&gt;)
        &lt;span style="color: blue"&gt;If &lt;/span&gt;i &lt;span style="color: blue"&gt;Mod &lt;/span&gt;2 = 0 &lt;span style="color: blue"&gt;Then
            &lt;/span&gt;IsEven = &lt;span style="color: blue"&gt;True
        Else
            &lt;/span&gt;IsEven = &lt;span style="color: blue"&gt;False
        End If
    End Function

&lt;/span&gt;&lt;/pre&gt;


&lt;p&gt;While VB.Net added a Return statement it still supports this legacy syntax (and it allows the two to be mixed within a single function).&amp;#160; The compiler models this by having a local of the same name of the function which is used to store the return value.&amp;#160; Returns from the function are rewritten as assignments to this local and then a return of the same local.&amp;#160; The debugger understands this hidden local and displays it during the debugging session.&amp;#160; This gives VB.Net the appearance of supporting Return value display when in reality it’s just a positive side effect of legacy support.&amp;#160; &lt;/p&gt;

&lt;p&gt;Quick Note:&amp;#160; In my experience when &lt;a href="http://stackoverflow.com/questions/591086/vs-get-returned-value-in-c-code"&gt;users ask&lt;/a&gt; for return value support in the debugger they typically want to see both &lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;The return value of the current function they're stepping through &lt;/li&gt;

  &lt;li&gt;The return value of functions which are stepped over (more heavily requested)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;VB.Net supports only the first one (via the described method) and C# supports neither.&amp;#160; &lt;/p&gt;

&lt;p&gt;I do agree it would be really nice if both languages supported #2 (it’s an incredibly useful feature in C++).&amp;#160; It is possible to do without CLR support but it involves the compiler generating a temporary for every function / property evaluated in a statement and lots of copying values around.&amp;#160; This can have a non-trivial impact on program performance even when not debugging and hence I think is unlikely to be done.&amp;#160; If #2 does come around it will likely be through the CLR debugger APIs providing access to the return values much in the way it provides access to the &lt;a href="http://msdn.microsoft.com/en-us/library/ms230540(pt-br,VS.90).aspx"&gt;current exception&lt;/a&gt;.&amp;#160; &lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10113852" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/jaredpar/archive/tags/VB/">VB</category><category domain="http://blogs.msdn.com/b/jaredpar/archive/tags/C_2300_/">C#</category><category domain="http://blogs.msdn.com/b/jaredpar/archive/tags/Debugging/">Debugging</category><category domain="http://blogs.msdn.com/b/jaredpar/archive/tags/Visual+Studio/">Visual Studio</category></item><item><title>Advanced Multitargeting in VB.Net</title><link>http://blogs.msdn.com/b/jaredpar/archive/2010/07/23/advanced-multitargeting-in-vb-net.aspx</link><pubDate>Fri, 23 Jul 2010 12:00:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10031358</guid><dc:creator>JaredPar MSFT</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/jaredpar/rsscomments.aspx?WeblogPostID=10031358</wfw:commentRss><comments>http://blogs.msdn.com/b/jaredpar/archive/2010/07/23/advanced-multitargeting-in-vb-net.aspx#comments</comments><description>&lt;p&gt;Multi-targeting is a feature introduced in Visual Studio 2008 which allows developers to use new versions of Visual Studio to target earlier versions of the .Net platform.&amp;#160; It allowed users to target both the new 3.5 and 3.0 and the previous 2.0 profile with the same IDE.&amp;#160; Visual Studio 2010 &lt;a href="http://msdn.microsoft.com/en-us/magazine/ff714560.aspx"&gt;continues this trend&lt;/a&gt; by adding support for CLR 4.0 and even allows for further sub-targeting through several &lt;a href="http://channel9.msdn.com/posts/funkyonex/Multi-Targeting-Deep-Dive-with-Visual-Basic-2010/"&gt;framework profiles&lt;/a&gt;.&amp;#160; &lt;/p&gt;  &lt;p&gt;At a compiler level this works by providing binary compatibility with previous versions of the CLR (or producing an error when it’s not possible).&amp;#160; It doesn’t warn developers about using new language constructs on older frameworks so long as they function in the target framework.&amp;#160; &lt;/p&gt;  &lt;p&gt;Take the following code sample as an example.&amp;#160; It is taking advantage of &lt;a href="http://blogs.msdn.com/b/vbteam/archive/2009/03/27/implicit-line-continuation-in-vb-10-tyler-whitney.aspx"&gt;implicit line continuations&lt;/a&gt; which is a feature introduced in VB.Net 10 and not available in Visual Studio 2008.&amp;#160; Since it’s just syntactic sugar it compiles just fine in an application targeting 4.0 or any previous version of the framework.&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;Dim &lt;/span&gt;query =
    &lt;span style="color: blue"&gt;From &lt;/span&gt;it &lt;span style="color: blue"&gt;In &lt;/span&gt;col
    &lt;span style="color: blue"&gt;Where &lt;/span&gt;it &lt;span style="color: blue"&gt;Mod &lt;/span&gt;2 = 0
    &lt;span style="color: blue"&gt;Select &lt;/span&gt;it * 3&lt;/pre&gt;

&lt;p&gt;In a limited set of scenarios though developers want to use Visual Studio 2010 to develop code which will also be compiled by a previous version of the compiler.&amp;#160; Hence they want warnings in Visual Studio when new language constructs are used.&amp;#160; &lt;/p&gt;

&lt;p&gt;The 10.0 version of vbc.exe introduced a new switch named &lt;a href="http://msdn.microsoft.com/en-us/library/dd547577.aspx"&gt;langversion&lt;/a&gt; to provide just that.&amp;#160; It allows developers to specify a version of the language to target.&amp;#160; The compiler will then issue an error when a language construct which was introduced in a later version is used.&amp;#160; This switch is not available from the IDE though and must be manually specified in the project file.&amp;#160; To do so edit the .vbproj file and add the following element under the main ItemGroup element.&lt;/p&gt;

&lt;pre class="code"&gt;  &lt;span style="color: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;PropertyGroup&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
    &amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;LangVersion&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;&lt;/span&gt;9&lt;span style="color: blue"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;LangVersion&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;
  &amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;PropertyGroup&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;

&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;Once the project is reloaded errors will start appearing for new language constructs.&amp;#160; Notice how our earlier sample now produces the errors for the usages of the new implicit line continuation construct.&amp;#160; &lt;/p&gt;

&lt;p&gt;&lt;a href="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-39-97-metablogapi/7612.image_5F00_4.png"&gt;&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" class="wlDisabledImage" title="image" border="0" alt="image" src="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-39-97-metablogapi/3173.image_5F00_thumb_5F00_1.png" width="640" height="547" /&gt;&lt;/a&gt;&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10031358" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/jaredpar/archive/tags/VB/">VB</category><category domain="http://blogs.msdn.com/b/jaredpar/archive/tags/Visual+Studio/">Visual Studio</category></item><item><title>Why is LINQ absent from debugger windows (Part 2)?</title><link>http://blogs.msdn.com/b/jaredpar/archive/2010/06/02/why-is-linq-absent-from-debugger-windows-part-2.aspx</link><pubDate>Wed, 02 Jun 2010 12:00:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10016054</guid><dc:creator>JaredPar MSFT</dc:creator><slash:comments>8</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/jaredpar/rsscomments.aspx?WeblogPostID=10016054</wfw:commentRss><comments>http://blogs.msdn.com/b/jaredpar/archive/2010/06/02/why-is-linq-absent-from-debugger-windows-part-2.aspx#comments</comments><description>&lt;p&gt;Some readers may remember an &lt;a href="http://blogs.msdn.com/jaredpar/archive/2009/08/26/why-no-linq-in-debugger-windows.aspx"&gt;article&lt;/a&gt; I published almost half a year ago about LINQ being absent from the debugger windows.&amp;#160; That post explored the initial design of the feature, it’s limitations and ultimately why it was absent but promised a future article on a slightly different approach.&amp;#160; It’s quite late but I’ve finally had some time to write the second part of this article [1]&lt;/p&gt;  &lt;p&gt;No, I didn’t forget about the article or really get too lazy.&amp;#160; The pace of Dev10 really picked up shortly after publishing that article and the follow up was put on the back burner.&amp;#160; This week I finally find myself with a bit of free time and decided to follow up on my promise.&amp;#160; &lt;/p&gt;  &lt;p&gt;First a quick refresher.&amp;#160; Features in the Expression Evaluator are started on the basis of having complete parity with the feature as it exists in the language and then paired down based on cost.&amp;#160; Having complete parity with LINQ is prohibitably costly due to it being much more of an ENC expression instead of an inspection one (the latter being the primary purpose of an expression evaluator).&amp;#160; Now comes the compromise phase. &lt;/p&gt;  &lt;p&gt;As stated in the previous article the most expensive portion of this design is adding ENC support to the Expression Evaluator.&amp;#160; ENC is necessary for true parity because closures in C# and VB.Net are mutable and requiring altering program state to implement.&amp;#160; The standard example is evaluating the following expression in the EE which modifies the value of a local variable.&lt;/p&gt;  &lt;pre class="code"&gt;((&lt;span style="color: #2b91af"&gt;Action&lt;/span&gt;)(() =&amp;gt; { local1 = 42; }))();&lt;/pre&gt;

&lt;p&gt;Properly implementing this requires program mutation not just inspection.&amp;#160; &lt;/p&gt;

&lt;p&gt;Now comes the compromise.&amp;#160; How often do users really want to do this?&amp;#160; In my observations the answer is rarely if ever.&amp;#160; When I talk with customers about LINQ in the debugger windows almost every single answer comes down to allowing filtering / where expressions.&amp;#160; These are inherently, but not strictly, non-mutating operations.&amp;#160; &lt;/p&gt;

&lt;pre class="code"&gt;list.Where(x =&amp;gt; x.Name == &lt;span style="color: #a31515"&gt;&amp;quot;Jared&amp;quot;&lt;/span&gt;);&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Cutting mutation is a huge advantage because we can forget about the impact into existing closures and alteration of program structure.&amp;#160; Instead we can generate new closures which copy the initial state of the values and work from there.&amp;#160; This removes all of the state tracking problems examined in the previous article.&amp;#160; &lt;/p&gt;

&lt;p&gt;If we cut mutation, and hence ENC, we can move to a different approach for generating code.&amp;#160; Instead of generating all of the types and methods in the current assembly with ENC, create a generated assembly in the target process which contains the new types and methods.&amp;#160; This can be done through existing technologies like Reflection.Emit.&amp;#160; &lt;/p&gt;

&lt;p&gt;So How does that change the cost of the feature?&amp;#160; If we look at the major feature list discussed in the previous article we’d only be left with the following&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;Converting expressions typed in the EE to IL &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Lets take a deeper look at this given our new proposed architecture.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Metadata Generation Service&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The debugger and expression evaluator live in a different process than the debugee.&amp;#160; Any generated lambda expression needs to be done in the debugee process.&amp;#160; Yet all of the information needed to create the lambda exists in the debugger process.&amp;#160; Implementing this feature requires that all of this data to be transferred between the processes.&amp;#160; In effect we’d have to serialize both the metadata and IL of the trees and send them across the process boundary.&amp;#160; &lt;/p&gt;

&lt;p&gt;Creating a DLL to host the service, defining the interfaces and calling them from the EE all have costs.&amp;#160; Yet many of these are done on every release and the cost is very much understood.&amp;#160; Due to the regularity with which we do this we can cost this part with high confidence. &lt;/p&gt;

&lt;p&gt;What’s expensive here is defining the format for the data transfer.&amp;#160; Today we don’t directly generate IL in our compilers but instead use services exposed by the CLR to do so.&amp;#160; We would need to define a new serialization format for transferring our representation of trees to the debugee process, deserializing this in the debugee and converting it to metadata and IL.&amp;#160; This is actually very costly when you consider all of the details&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Needs to work in both a 32 and 64 bit environment &lt;/li&gt;

  &lt;li&gt;The sheer amount of data as the number of nodes in our trees is quite large &lt;/li&gt;

  &lt;li&gt;Data is transferred from a native process to a managed one so the structure for serializing data gets defined twice &lt;/li&gt;

  &lt;li&gt;Versioning: 
    &lt;ul&gt;
      &lt;li&gt;This service must support both the current and new versions of the EE &lt;/li&gt;

      &lt;li&gt;The serialization format must be able to handle the changes we make to our nodes over the course of several releases &lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;

  &lt;li&gt;Performance &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Of all of these “versioning” is the biggest cost.&amp;#160; All to often we don’t consider versioning when designing EE features and it comes back to haunt us in the long term.&amp;#160;&amp;#160; To implement such a large feature and not consider the versioning aspects would be a huge mistake.&amp;#160; &lt;/p&gt;

&lt;p&gt;The lack of previous work in this area and the overall size produces a feature with a high cost which has low confidence.&amp;#160; Not what a manager wants to hear. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Converting Expressions in the EE to IL&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The expression evaluator does not actually compile expressions down into IL.&amp;#160; Instead it compiles it down to a low level semantic tree which is then directly interpreted by the expression evaluator.&amp;#160; &lt;/p&gt;

&lt;p&gt;This approach grants a lot of flexibility to the EE and allows us to evaluate expressions that are not necessarily valid at the current place in the program.&amp;#160; For example the ability to directly evaluate object id expressions.&amp;#160; This flexibility hurts us here because it creates a subset of expressions which are not, or at least very difficult to, translate to IL.&amp;#160; How would an object id expression for instance be expressed in IL?&amp;#160; &lt;/p&gt;

&lt;p&gt;The problem is not just limited to object id expressions but also include a host of other items allowed in the EE.&amp;#160; There are too many to list in this article but suffice it to say this is not a trivial problem to solve [2].&amp;#160; Any cost for this area would have at best a medium level of confidence. &lt;/p&gt;

&lt;p&gt;The next problem with this approach is that our infrastructure which generates IL is heavily geared towards doing so for EXEs and DLLs.&amp;#160; It has been so for every release of our code base and contains a lot of code very specific to this process.&amp;#160; Converting this to be more general purpose is very costly at this point.&amp;#160; It would entail almost a complete rewrite of those components.&amp;#160; &lt;/p&gt;

&lt;p&gt;Once again this cost in itself is not prohibitive but does add up.&amp;#160; Really it amounts to a known type of refactoring with medium to high confidence.&amp;#160; &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Wait there’s more: Don’t forget testing&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;There are two costs to consider for the testing of this new feature.&amp;#160; The first is the straight forward costs you get with any new features.&amp;#160; This is a pretty standard and well understood process.&amp;#160; The language side of the feature is not too difficult to test.&amp;#160; The cost really starts adding up though when you consider all of the other parts which can go wrong: loading DLL’s into the process, 32 / 64 bit issues, making sure all instructions serialize, versioning, etc …&lt;/p&gt;

&lt;p&gt;The second more hidden cost though is the impact of this new feature on existing ones.&amp;#160; Consider again that today all expressions typed into the EE are interpreted.&amp;#160; However with our current design if the expression was inside of a lambda expression it would be executed not interpreted.&amp;#160; This is a completely different process and would require a completely different set of tests to verify it’s functionality. &lt;/p&gt;

&lt;p&gt;In effect this would double the cost for QA for all existing features as they’d need to be tested inside a lambda expression.&amp;#160; This is an enormous cost and one that cannot be ignored.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;In summary&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Here is a summary of the larger cost items&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Define a version friendly serialization format for transferring metadata and IL across the native and managed boundaries &lt;/li&gt;

  &lt;li&gt;Implement both the native serializer and managed deserializer for this format &lt;/li&gt;

  &lt;li&gt;Implementing a metadata generation service &lt;/li&gt;

  &lt;li&gt;All of the work around getting this DLL into the target process &lt;/li&gt;

  &lt;li&gt;Finding solutions for generating IL for all expressions which don’t directly map to IL &lt;/li&gt;

  &lt;li&gt;Refactoring our existing compiler infrastructure to be friendly to generating IL for the EE &lt;/li&gt;

  &lt;li&gt;QA costs for testing this feature &lt;/li&gt;

  &lt;li&gt;QA work to double test every type of expression (inside and outside of a lambda) &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This doesn’t take into account a lot of the smaller items I’ve ignored [3] or the items we’d only find once we started implementing.&amp;#160; This is after all a very large feature and those always have hidden costs that aren’t found until implementation hits a certain point.&amp;#160; &lt;/p&gt;

&lt;p&gt;I’m very hesitant to put a strict time estimate on this feature (it would almost certainly be wrong given the hidden costs and the lack of confidence in estimating several areas).&amp;#160; To put it in a bit of context though, I would estimate it as large and likely larger than any other feature I’ve worked on since I joined Microsoft.&amp;#160; &lt;/p&gt;

&lt;p&gt;Once again I’m not writing this blog post to justify why we won’t ever implement LINQ debugging.&amp;#160; Instead I write this to justify why we haven’t done it up till this point.&amp;#160; This is a feature which has clear customer value and a fair bit of demand and I want to help customers understand our decision making process in this area. &lt;/p&gt;

&lt;p&gt;I’m still very hopeful this feature will make it into the product at a future release.&amp;#160; Perhaps we’ll find a cheaper route we’re not currently considering.&amp;#160; Or maybe a future feature we need will offset some of the costs here.&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;[1] This gap is certainly a personal record and one I hope to never beat&lt;/p&gt;

&lt;p&gt;[2] One day I may write about these items because pretty much all exist to support a richer user experience.&amp;#160; &lt;/p&gt;

&lt;p&gt;[3] Anonymous types, transparent identifiers and VB generated delegates for starters&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10016054" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/jaredpar/archive/tags/VB/">VB</category><category domain="http://blogs.msdn.com/b/jaredpar/archive/tags/C_2300_/">C#</category><category domain="http://blogs.msdn.com/b/jaredpar/archive/tags/Debugging/">Debugging</category><category domain="http://blogs.msdn.com/b/jaredpar/archive/tags/LINQ/">LINQ</category><category domain="http://blogs.msdn.com/b/jaredpar/archive/tags/Expression+Evaluator/">Expression Evaluator</category></item><item><title>Nothing is private in the debugger (part 2)</title><link>http://blogs.msdn.com/b/jaredpar/archive/2010/05/19/nothing-is-private-in-the-debugger-part-2.aspx</link><pubDate>Wed, 19 May 2010 12:00:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10018195</guid><dc:creator>JaredPar MSFT</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/jaredpar/rsscomments.aspx?WeblogPostID=10018195</wfw:commentRss><comments>http://blogs.msdn.com/b/jaredpar/archive/2010/05/19/nothing-is-private-in-the-debugger-part-2.aspx#comments</comments><description>&lt;p&gt;In a &lt;a href="http://blogs.msdn.com/jaredpar/archive/2010/05/17/the-debugger-is-different.aspx"&gt;previous post&lt;/a&gt; I discussed how accessibility is ignored when evaluating expressions in the debugger and the unexpected scenarios that it creates.&amp;#160; One case I neglected to mention in that article is how this behavior works with the VB late binding engine.&amp;#160; &lt;/p&gt;  &lt;p&gt;The expression evaluator only relaxes accessibility rules when binding an expression.&amp;#160; This is possible because the expression evaluator effectively hosts the compiler and can override items like accessibility checks.&lt;/p&gt;  &lt;p&gt;In the case of late binding the compiler only participates in building an expression that will call into the VB runtime late binding engine.&amp;#160; The accessibility determination for the target of late bound call occurs in the VB runtime and is not (currently) overidable by the expression evaluator.&amp;#160; &lt;/p&gt;  &lt;p&gt;Late bound access combined with static access can lead to additional confusing behavior.&amp;#160; For example.&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;Class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;C1
    &lt;/span&gt;&lt;span style="color: blue"&gt;Private &lt;/span&gt;Field1 &lt;span style="color: blue"&gt;As Integer
    Public Property &lt;/span&gt;Property1 &lt;span style="color: blue"&gt;As Integer
End Class

Module &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Module1

    &lt;/span&gt;&lt;span style="color: blue"&gt;Sub &lt;/span&gt;Main()
        &lt;span style="color: blue"&gt;Dim &lt;/span&gt;v1 &lt;span style="color: blue"&gt;As New &lt;/span&gt;&lt;span style="color: #2b91af"&gt;C1
        &lt;/span&gt;&lt;span style="color: blue"&gt;Dim &lt;/span&gt;v2 &lt;span style="color: blue"&gt;As Object &lt;/span&gt;= v1
        &lt;span style="color: blue"&gt;Stop
    End Sub

End Module

&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;When the following code is run, all members are accessible from the v1 local.&amp;#160; It is statically typed to C1 and hence the expression evaluator can ignore accessibility and access the values.&lt;/p&gt;

&lt;p&gt;&lt;a href="http://blogs.msdn.com/blogfiles/jaredpar/WindowsLiveWriter/Nothingisprivateinthedebuggerpart2_10EBA/image_2.png"&gt;&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://blogs.msdn.com/blogfiles/jaredpar/WindowsLiveWriter/Nothingisprivateinthedebuggerpart2_10EBA/image_thumb.png" width="628" height="170" /&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;The local v2 references the same object instance so it’s reasonable to assume it can access the same values.&amp;#160; However because it’s statically typed as object, calls like v1.Field1 actually turn into late bound calls and hence are subject to the rules of the late binder.&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;&lt;a href="http://blogs.msdn.com/blogfiles/jaredpar/WindowsLiveWriter/Nothingisprivateinthedebuggerpart2_10EBA/image_4.png"&gt;&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://blogs.msdn.com/blogfiles/jaredpar/WindowsLiveWriter/Nothingisprivateinthedebuggerpart2_10EBA/image_thumb_1.png" width="628" height="165" /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Evaluation of Field1 fails here because the late binder does not allow access to private fields.&amp;#160; Property1 evaluates just fine though because it’s public. &lt;/p&gt;

&lt;p&gt;We are considering changing this behavior in a future release.&amp;#160; As usual no promises. &lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10018195" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/jaredpar/archive/tags/VB/">VB</category><category domain="http://blogs.msdn.com/b/jaredpar/archive/tags/Debugging/">Debugging</category><category domain="http://blogs.msdn.com/b/jaredpar/archive/tags/Visual+Studio/">Visual Studio</category></item><item><title>Nothing is private in the debugger</title><link>http://blogs.msdn.com/b/jaredpar/archive/2010/05/17/the-debugger-is-different.aspx</link><pubDate>Mon, 17 May 2010 12:00:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10012693</guid><dc:creator>JaredPar MSFT</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/jaredpar/rsscomments.aspx?WeblogPostID=10012693</wfw:commentRss><comments>http://blogs.msdn.com/b/jaredpar/archive/2010/05/17/the-debugger-is-different.aspx#comments</comments><description>&lt;p&gt;The goal of the debugger is to provide rich inspection capabilities for a process.&amp;#160; The main method of inspection is through the evaluation of textual expressions which is handled by a language specific component known as the &lt;a href="http://msdn.microsoft.com/en-us/library/bb144988.aspx"&gt;expression evaluator&lt;/a&gt;. This component is the data provider for a good portion of the debugger windows (watch, locals, autos, etc …)&lt;/p&gt;  &lt;p&gt;The expression evaluators go to great lengths to ensure that expression in the debugger evaluate exactly as it would if the expression was typed at the current place in the file where the debugger was stopped.&amp;#160; To do otherwise only leads to user confusion.&amp;#160; Often making it harder to track down the issue you’re currently debugging and resulting in a loss in faith in the quality of the debugger and language.&lt;/p&gt;  &lt;p&gt;Occasionally, or not so occasionally, the goals of providing high fidelity in evaluation and rich inspection conflict.&amp;#160; When this occurs we have to weight the tradeoffs of confusing users by changing the semantics of the language vs. the resulting increased capabilities in the debugger.&amp;#160; &lt;/p&gt;  &lt;p&gt;One example is accessibility.&amp;#160; Languages have strong notions of accessibility which is enforced by the compiler and CLR.&amp;#160; In order to provide rich inspection though the debugger must be able to access all available data including items which are not accessible by the language.&amp;#160; To do otherwise might arbitrarily hide that one piece of data a developer needs to solve the problem at hand.&amp;#160;&amp;#160; Hence accessibility is one case where the expression evaluators bend language rules and allow expressions to access data without accessibility checks.&amp;#160; &lt;/p&gt;  &lt;p&gt;One the surface this doesn’t seem like a big change.&amp;#160; It’s an additive change allowing users to see more fields, properties and methods.&amp;#160; In the majority case it’s as simple as that and leads to little confusion.&amp;#160; &lt;/p&gt;  &lt;p&gt;However even seemingly simple changes like removing accessibility checks can lead to very surprising behavior for our users.&amp;#160; Recently our QA team filed a bug that illustrates this point.&amp;#160; &lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;Module &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Module1
    &lt;/span&gt;&lt;span style="color: blue"&gt;Class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Base
        &lt;/span&gt;&lt;span style="color: blue"&gt;Private &lt;/span&gt;Field1 &lt;span style="color: blue"&gt;As Integer &lt;/span&gt;= 55
    &lt;span style="color: blue"&gt;End Class

    Class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Derived
        &lt;/span&gt;&lt;span style="color: blue"&gt;Inherits &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Base
        &lt;/span&gt;&lt;span style="color: blue"&gt;Sub &lt;/span&gt;Method1()
            Field1 = 72
            &lt;span style="color: blue"&gt;Stop
        End Sub
    End Class

    Sub &lt;/span&gt;Main()
        &lt;span style="color: blue"&gt;Dim &lt;/span&gt;x &lt;span style="color: blue"&gt;As New &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Derived
        &lt;/span&gt;x.Method1()
    &lt;span style="color: blue"&gt;End Sub

End Module
Module &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Module2
    &lt;/span&gt;&lt;span style="color: blue"&gt;Public &lt;/span&gt;Field1 &lt;span style="color: blue"&gt;As Integer
End Module

&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;QA noted that if they ran this code and typed Field1 in the watch window that the value showed 55 instead of 72.&amp;#160; This was noted as a bug because Field1 was set to 72 on the line before.&amp;#160; &lt;/p&gt;

&lt;p&gt;Interestingly enough though is that this behavior, while very confusing, is actually “By Design”.&amp;#160; &lt;/p&gt;

&lt;p&gt;The reason why is that when evaluating expressions in the debugger nothing is private.&amp;#160; Knowing this reconsider what it means to evaluate Field1 inside of Method1 with both instances being Public.&amp;#160; The correct binding is Base::Field1 since the VB language prefers instance fields over Module fields if they are both accessible.&amp;#160; The expression evaluator correctly evaluates this as 55.&lt;/p&gt;

&lt;p&gt;However when the code was compiled accessibility checks were in place.&amp;#160; This mean that Base::Field1 was not considered since it was private and inaccessible.&amp;#160; The compiler instead correctly bound to Module2::Field1 and this is the field which is used when the code is running.&amp;#160; Developers can verify this by evaluating Module2.Field1 in any of the debugger windows.&amp;#160; &lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10012693" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/jaredpar/archive/tags/VB/">VB</category><category domain="http://blogs.msdn.com/b/jaredpar/archive/tags/Debugging/">Debugging</category><category domain="http://blogs.msdn.com/b/jaredpar/archive/tags/Gotcha/">Gotcha</category><category domain="http://blogs.msdn.com/b/jaredpar/archive/tags/Expression+Evaluator/">Expression Evaluator</category></item><item><title>The many cases of ByRef</title><link>http://blogs.msdn.com/b/jaredpar/archive/2010/01/21/the-many-cases-of-byref.aspx</link><pubDate>Thu, 21 Jan 2010 13:00:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9892877</guid><dc:creator>JaredPar MSFT</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/jaredpar/rsscomments.aspx?WeblogPostID=9892877</wfw:commentRss><comments>http://blogs.msdn.com/b/jaredpar/archive/2010/01/21/the-many-cases-of-byref.aspx#comments</comments><description>&lt;p&gt;One of the overlooked or simply misunderstood features of the VB language is calling a function which has a ByRef parameter.&amp;#160; Most languages support only a single method of passing parameters by reference [1], that is the scenarios directly supported by the CLR.&amp;#160; The CLR has a lot of restrictions on the type of values it supports for ByRef parameters and these restrictions get in the way of VB’s goal to be a flexible language that strives to get out of the way of the user.&amp;#160; Hence the compiler goes to great lengths to be flexible and support multiple avenues of ByRef passing, much beyond what the CLR natively allows.&lt;/p&gt;  &lt;p&gt;This article will explore these different mechanisms.&amp;#160; In order to reduce the code samples, I will be using the following 2 methods to explain the different mechanisms of ByRef Passing&lt;/p&gt;  &lt;pre class="code"&gt;    &lt;span style="color: blue"&gt;Sub &lt;/span&gt;FunctionWithInt(&lt;span style="color: blue"&gt;ByRef &lt;/span&gt;p1 &lt;span style="color: blue"&gt;As Integer&lt;/span&gt;)
        p1 = &lt;span style="color: brown"&gt;42
    &lt;/span&gt;&lt;span style="color: blue"&gt;End Sub
    Sub &lt;/span&gt;FunctionWithObject(&lt;span style="color: blue"&gt;ByRef &lt;/span&gt;p1 &lt;span style="color: blue"&gt;As Object&lt;/span&gt;, &lt;span style="color: blue"&gt;ByVal &lt;/span&gt;p2 &lt;span style="color: blue"&gt;As Object&lt;/span&gt;)
        p1 = p2
    &lt;span style="color: blue"&gt;End Sub&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;&lt;strong&gt;CLR ByRef&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The first is to simply use the CLR concept of passing by reference as defined by section 12.4.1.5.2 and 12.1.6.1 of the CLI specification.&amp;#160; Any variable which meets any of the following criteria, does not require a type conversion, and is passed to a ByRef parameter will be passed directly in the CLR.&amp;#160; &lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Argument of the current method &lt;/li&gt;

  &lt;li&gt;Local variable &lt;/li&gt;

  &lt;li&gt;Member Field of an object &lt;/li&gt;

  &lt;li&gt;Static Field &lt;/li&gt;

  &lt;li&gt;Array Element &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;No special code is needed or generated for this scenario.&amp;#160; &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Copy Back ByRef&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;While the CLR method of passing ByRef is very flexible, it disallows a number of useful scenarios.&amp;#160; The most prominent of which is properties.&amp;#160; Properties do not meet the CLR requirements for ByRef because under the hood they are simply a pair of function calls.&amp;#160; The result of a function call cannot be directly passed by reference.&amp;#160; &lt;/p&gt;

&lt;p&gt;Without any language intervention this can be very confusing to users.&amp;#160; Properties are very often simple get/set wrappers around fields and have almost the exact same usage scenarios.&amp;#160; To the point that most users don’t see a functional difference between the two.&amp;#160; Auto-implemented properties blur this line even further.&amp;#160; Not being able to pass them ByRef creates an unacceptable inconsistency in their usage.&lt;/p&gt;

&lt;p&gt;VB removes this inconsistency and allows properties to be passed by reference.&amp;#160; This is implemented under the hood by means of a temporary variable.&amp;#160; Temporaries are just local variables and hence can be passed by reference.&amp;#160; The property value is assigned to a temporary which is then passed by reference and then after wards is copied back into the original property.&lt;/p&gt;

&lt;p&gt;For example, take the following code sample &lt;/p&gt;

&lt;pre style="width: 816px; height: 163px" class="code"&gt;    &lt;span style="color: blue"&gt;Class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;C1
        &lt;/span&gt;&lt;span style="color: blue"&gt;Public Property &lt;/span&gt;P1 &lt;span style="color: blue"&gt;As Integer
        Public &lt;/span&gt;P2 &lt;span style="color: blue"&gt;As Integer
    End Class
    Sub &lt;/span&gt;CopyBackByRef()
        &lt;span style="color: blue"&gt;Dim &lt;/span&gt;v1 = &lt;span style="color: blue"&gt;New &lt;/span&gt;&lt;span style="color: #2b91af"&gt;C1
        &lt;/span&gt;FunctionWithInt(v1.P1)
    &lt;span style="color: blue"&gt;End Sub

&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;This will result in essentially the following code being generated&lt;/p&gt;

&lt;pre class="code"&gt;    &lt;span style="color: blue"&gt;Sub &lt;/span&gt;CopyBackByRef_Explained()
        &lt;span style="color: blue"&gt;Dim &lt;/span&gt;v1 = &lt;span style="color: blue"&gt;New &lt;/span&gt;&lt;span style="color: #2b91af"&gt;C1
        &lt;/span&gt;&lt;span style="color: blue"&gt;Dim &lt;/span&gt;vbTemp = v1.P1
        FunctionWithInt(vbTemp)
        v1.P1 = vbTemp
    &lt;span style="color: blue"&gt;End Sub

&lt;/span&gt;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;This type of ByRef passing is used in the following 2 scenarios&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;The value is a Property containing both a getter and setter.&amp;#160; &lt;/li&gt;

  &lt;li&gt;Passing the value to the function requires a conversion. &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The first can be done with even the strictest Option settings.&amp;#160; However #2 can only be used with Option Strict Off because it requires an implicit narrowing conversion.&amp;#160; &lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Don’t Copy Back ByRef&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;So far we’ve only looked at scenarios where the user wants to actually see the value returned from the ByRef parameter.&amp;#160; There are many scenarios where the language can infer the user does not care about the return value of the function.&amp;#160; For example, what if I just want to pass a constant value?&amp;#160; &lt;/p&gt;

&lt;pre class="code"&gt;    &lt;span style="color: blue"&gt;Sub &lt;/span&gt;DontCopyBackByRef()
        FunctionWithInt(&lt;span style="color: brown"&gt;42&lt;/span&gt;)
    &lt;span style="color: blue"&gt;End Sub

&lt;/span&gt;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;This code is legal in VB and represents another method of passing by ref.&amp;#160; This is very similar to the copy back method of passing by reference.&amp;#160; The only difference is that it never copies the value back.&amp;#160; It essentially generates the following code&lt;/p&gt;

&lt;pre class="code"&gt;    &lt;span style="color: blue"&gt;Sub &lt;/span&gt;DontCopyBackByRef_Explained()
        &lt;span style="color: blue"&gt;Dim &lt;/span&gt;vbTemp = &lt;span style="color: brown"&gt;42
        &lt;/span&gt;FunctionWithInt(vbTemp)
    &lt;span style="color: blue"&gt;End Sub
&lt;/span&gt;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;This type of ByRef is used in any scenario where the value being passed cannot be assigned to.&amp;#160; For example&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;The result of function calls &lt;/li&gt;

  &lt;li&gt;Read Only Properties &lt;/li&gt;

  &lt;li&gt;Constant Values &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Maybe Copy Back ByRef&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Up until now we’ve examined cases where the compiler can examine both the value being passed and the parameter it is being passed to and make a determination about what direction the data needs to move in.&amp;#160; What about late binding?&lt;/p&gt;

&lt;pre class="code"&gt;    &lt;span style="color: blue"&gt;Sub &lt;/span&gt;MaybeCopyBackByRef()
        &lt;span style="color: blue"&gt;Dim &lt;/span&gt;v1 &lt;span style="color: blue"&gt;As Object &lt;/span&gt;= &lt;span style="color: blue"&gt;Me
        Dim &lt;/span&gt;v2 = &lt;span style="color: brown"&gt;13
        &lt;/span&gt;v1.FunctionWithInt(v2)
    &lt;span style="color: blue"&gt;End Sub
&lt;/span&gt;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Here v1 is typed to object and hence FunctionWithInt is being accessed via late binding.&amp;#160; In this case the compiler doesn’t know the actual method being invoked runtime.&amp;#160; Hence it cannot know up front if the parameters are ByRef or ByVal and cannot make an up front decision on the variable passing mechanism.&amp;#160; &lt;/p&gt;

&lt;p&gt;In order to make late binding invokes flow as smoothly as normal method invokes, the compiler will generate code to conditionally update the original value based on the runtime information about the parameter.&amp;#160; The late binder communicates this information via an array of Boolean values, one for each parameter passed to the function.&amp;#160; The compiler will initialize this array with true for any values it knows are updatable and false for values that are not.&amp;#160; The late binder will then examine every parameter to the function and set the corresponding index in the array to false if the method parameter is ByVal.&amp;#160; If it is ByRef the returned value from the function will be copied back into the original parameter array.&lt;/p&gt;

&lt;p&gt;The resulting code looks a bit like this.&amp;#160; You can ignore all of the Nothing values as they are not important for this discussion.&amp;#160; &lt;/p&gt;

&lt;pre class="code"&gt;    &lt;span style="color: blue"&gt;Sub &lt;/span&gt;MaybeCopyBackByRef_Explained()
        &lt;span style="color: blue"&gt;Dim &lt;/span&gt;v1 &lt;span style="color: blue"&gt;As Object &lt;/span&gt;= &lt;span style="color: blue"&gt;Me
        Dim &lt;/span&gt;v2 = &lt;span style="color: brown"&gt;13
        &lt;/span&gt;&lt;span style="color: blue"&gt;Dim &lt;/span&gt;parameters = &lt;span style="color: blue"&gt;New Object&lt;/span&gt;() {v2}
        &lt;span style="color: blue"&gt;Dim &lt;/span&gt;isByRef = &lt;span style="color: blue"&gt;New Boolean&lt;/span&gt;() {&lt;span style="color: blue"&gt;True&lt;/span&gt;}
        &lt;span style="color: #2b91af"&gt;NewLateBinding&lt;/span&gt;.LateCall(v1, &lt;span style="color: blue"&gt;Nothing&lt;/span&gt;, &lt;span style="color: #a31515"&gt;&amp;quot;FunctionWithInt&amp;quot;&lt;/span&gt;, parameters, &lt;span style="color: blue"&gt;Nothing&lt;/span&gt;, &lt;span style="color: blue"&gt;Nothing&lt;/span&gt;, isByRef, &lt;span style="color: blue"&gt;True&lt;/span&gt;)
        &lt;span style="color: blue"&gt;If &lt;/span&gt;(isByRef(&lt;span style="color: brown"&gt;0&lt;/span&gt;)) &lt;span style="color: blue"&gt;Then
            &lt;/span&gt;v2 = &lt;span style="color: blue"&gt;CInt&lt;/span&gt;(parameters(&lt;span style="color: brown"&gt;0&lt;/span&gt;))
        &lt;span style="color: blue"&gt;End If
    End Sub
&lt;/span&gt;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;[1] Starting with version 4.0, C# now supports two versions of reference passing.&amp;#160; In addition to the one available since 1.0 the ref modifier is now optional when making an interop call to a COM object: &lt;a href="http://mutelight.org/articles/new-features-in-c-sharp-4.html"&gt;http://mutelight.org/articles/new-features-in-c-sharp-4.html&lt;/a&gt;&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9892877" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/jaredpar/archive/tags/VB/">VB</category></item><item><title>Dev Connection Talk Slides and Code</title><link>http://blogs.msdn.com/b/jaredpar/archive/2009/12/02/dev-connection-talk-slides-and-code.aspx</link><pubDate>Wed, 02 Dec 2009 21:21:45 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9931627</guid><dc:creator>JaredPar MSFT</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/jaredpar/rsscomments.aspx?WeblogPostID=9931627</wfw:commentRss><comments>http://blogs.msdn.com/b/jaredpar/archive/2009/12/02/dev-connection-talk-slides-and-code.aspx#comments</comments><description>&lt;p&gt;Thanks to everyone who attended my sessions at Dev Connections.&amp;#160; I’ve posted the material for both of my talks on my SkyDrive account.&amp;#160; This includes the slides and projects.&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;a href="http://cid-dc25b20f65f628f8.skydrive.live.com/browse.aspx/Public/DevConnections2009"&gt;http://cid-dc25b20f65f628f8.skydrive.live.com/browse.aspx/Public/DevConnections2009&lt;/a&gt;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Please let me know if you have any questions or problems with the materials or any additional feedback about the sessions.&amp;#160; &lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9931627" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/jaredpar/archive/tags/VB/">VB</category></item><item><title>Speaking at Dev Connections in Las Vegas Next Week</title><link>http://blogs.msdn.com/b/jaredpar/archive/2009/11/03/speaking-at-dev-connections-in-las-vegas-next-week.aspx</link><pubDate>Tue, 03 Nov 2009 16:51:04 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9916831</guid><dc:creator>JaredPar MSFT</dc:creator><slash:comments>1</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/jaredpar/rsscomments.aspx?WeblogPostID=9916831</wfw:commentRss><comments>http://blogs.msdn.com/b/jaredpar/archive/2009/11/03/speaking-at-dev-connections-in-las-vegas-next-week.aspx#comments</comments><description>&lt;p&gt;Next week I will be speaking at &lt;a href="http://www.devconnections.com/shows/FALL2009VS/default.asp?s=136"&gt;Dev Connections&lt;/a&gt; in Las Vegas.&amp;#160; I will be running the following sessions&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;VMS02: Future Directions for Visual Basic&lt;/li&gt;    &lt;li&gt;VMS04: Microsoft Visual Basic IDE Tips and Tricks&lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Both of these talks will spend a bit of time talking about all of the progress and exciting new features we’ve added in Dev10.&amp;#160; Given I primarily work on the IDE these days, expect a bit of IDE content to work it’s way into the Future Directions talk as well.&amp;#160; &lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9916831" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/jaredpar/archive/tags/VB/">VB</category></item><item><title>Why is LINQ absent from debugger windows?</title><link>http://blogs.msdn.com/b/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>JaredPar MSFT</dc:creator><slash:comments>9</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/jaredpar/rsscomments.aspx?WeblogPostID=9877055</wfw:commentRss><comments>http://blogs.msdn.com/b/jaredpar/archive/2009/08/26/why-no-linq-in-debugger-windows.aspx#comments</comments><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/b/jaredpar/archive/tags/VB/">VB</category><category domain="http://blogs.msdn.com/b/jaredpar/archive/tags/Closures/">Closures</category><category domain="http://blogs.msdn.com/b/jaredpar/archive/tags/C_2300_/">C#</category><category domain="http://blogs.msdn.com/b/jaredpar/archive/tags/Debugging/">Debugging</category><category domain="http://blogs.msdn.com/b/jaredpar/archive/tags/Lambda/">Lambda</category><category domain="http://blogs.msdn.com/b/jaredpar/archive/tags/LINQ/">LINQ</category></item><item><title>Extension Methods and ByRef targets</title><link>http://blogs.msdn.com/b/jaredpar/archive/2008/12/11/extension-methods-and-byref-targets.aspx</link><pubDate>Thu, 11 Dec 2008 16:00:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9189036</guid><dc:creator>JaredPar MSFT</dc:creator><slash:comments>7</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/jaredpar/rsscomments.aspx?WeblogPostID=9189036</wfw:commentRss><comments>http://blogs.msdn.com/b/jaredpar/archive/2008/12/11/extension-methods-and-byref-targets.aspx#comments</comments><description>&lt;p&gt;One of the seldom used, and often unknown, features of VB extension methods is that the argument of the extension method (the first parameter) can be passed by reference.&amp;#160; This gives extension methods the power to change the reference that was used to invoke the value!&amp;#160; &lt;/p&gt;  &lt;p&gt;Obviously this can produce unexpected but often amusing behavior.&amp;#160; The following sample prints “False”.&lt;/p&gt;  &lt;pre class="code"&gt;    &amp;lt;Extension()&amp;gt; _
    &lt;span style="color: blue"&gt;Public Sub &lt;/span&gt;EnsureNotNull(&lt;span style="color: blue"&gt;ByRef &lt;/span&gt;str &lt;span style="color: blue"&gt;As String&lt;/span&gt;)
        &lt;span style="color: blue"&gt;If &lt;/span&gt;str &lt;span style="color: blue"&gt;Is Nothing Then
            &lt;/span&gt;str = &lt;span style="color: blue"&gt;String&lt;/span&gt;.Empty
        &lt;span style="color: blue"&gt;End If
    End Sub

    Sub &lt;/span&gt;Example(&lt;span style="color: blue"&gt;ByVal &lt;/span&gt;p1 &lt;span style="color: blue"&gt;As String&lt;/span&gt;)
        p1.EnsureNotNull()
        Console.WriteLine(&lt;span style="color: #a31515"&gt;&amp;quot;{0}&amp;quot;&lt;/span&gt;, p1 &lt;span style="color: blue"&gt;Is Nothing&lt;/span&gt;)
    &lt;span style="color: blue"&gt;End Sub

    Sub &lt;/span&gt;Main()
        Example(&lt;span style="color: blue"&gt;Nothing&lt;/span&gt;)
    &lt;span style="color: blue"&gt;End Sub
&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;I think people will look at this example and either cringe, call it terrible code or get excited.&amp;#160; Personally I’m somewhere between cringing and getting excited (in fact I’m doing both).&amp;#160; But before people think I’ve gone off the deep end I don’t plan on checking this in any time soon (and yes I think it’s a bad idea).&lt;/p&gt;

&lt;p&gt;Why?&amp;#160; The feature is fun to play with and can create some interesting samples but it can also just as easily lead to very bad and unanticipated behavior.&amp;#160; For instance what if instead of making sure something wasn’t Nothing, the code made the argument Nothing?&amp;#160; &lt;/p&gt;

&lt;pre class="code"&gt;&amp;lt;Extension()&amp;gt; _
&lt;span style="color: blue"&gt;Sub &lt;/span&gt;EvilMethod(&lt;span style="color: blue"&gt;ByRef &lt;/span&gt;p1 &lt;span style="color: blue"&gt;As Object&lt;/span&gt;)
    p1 = &lt;span style="color: blue"&gt;Nothing
End Sub

Sub &lt;/span&gt;Example2()
    &lt;span style="color: blue"&gt;Dim &lt;/span&gt;s &lt;span style="color: blue"&gt;As New &lt;/span&gt;Student()
    s.PrintClass()
    s.EvilMethod()
    s.PrintName()   &lt;span style="color: green"&gt;' Causes a NullReferenceException
&lt;/span&gt;&lt;span style="color: blue"&gt;End Sub&lt;/span&gt;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;The code runs and throws an exception.&amp;#160; A developer attaches a debugger, looks at the exception but immediately notes there are 2 other method calls just above.&amp;#160; How could they succeed but the last throw a NullReferenceException???&amp;#160; Certainly this may be a fun joke but in production code a fellow developer would not be amused.&amp;#160; &lt;p&gt;More importantly though the behavior when passing an extension method target by reference is flat out unexpected.&amp;#160; Who expects what appears to an instance method call to be able to modify “Me/this?”&amp;#160; Probably not too many people.&amp;#160; Coding is difficult enough without creating patterns that will blow away anyone who owns your code down the line.&amp;#160; Code should do it’s best to be clear and produce predictable results.&lt;/p&gt;

&lt;p&gt;Still, an interesting feature to toy with. &lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9189036" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/jaredpar/archive/tags/VB/">VB</category><category domain="http://blogs.msdn.com/b/jaredpar/archive/tags/Extension+Methods/">Extension Methods</category><category domain="http://blogs.msdn.com/b/jaredpar/archive/tags/Humor/">Humor</category></item><item><title>Properly handling a WinForms Timer event</title><link>http://blogs.msdn.com/b/jaredpar/archive/2008/10/27/properly-handling-a-winforms-timer-event.aspx</link><pubDate>Mon, 27 Oct 2008 15:00:07 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9017488</guid><dc:creator>JaredPar MSFT</dc:creator><slash:comments>4</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/jaredpar/rsscomments.aspx?WeblogPostID=9017488</wfw:commentRss><comments>http://blogs.msdn.com/b/jaredpar/archive/2008/10/27/properly-handling-a-winforms-timer-event.aspx#comments</comments><description>&lt;p&gt;The WinForms &lt;a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.timer.aspx"&gt;Timer&lt;/a&gt; class allows the user to perform a particular action at a set interval.&amp;#160; Timer objects fire a &lt;a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.timer.tick.aspx"&gt;Tick&lt;/a&gt; event at the set time which users can easily respond to.&amp;#160; This is very useful if a developer wants to check for a particular condition say every 2 seconds ( for the remainder of this article I'm going to use 2 seconds as a practical example even though it's really any arbitrary time period).&lt;/p&gt;  &lt;p&gt;Occasionally users are surprised to find that the Tick event will fire much faster than they are expecting.&amp;#160; Instead of waiting for 2 seconds between calls, they event will fire almost immediately after one is finished processing. &lt;/p&gt;  &lt;p&gt;What's going on here is a side effect of how this event works under the hood.&amp;#160; The interval for the timer event is calculated in real world time.&amp;#160; So quite literally every 2 seconds Windows will consider the internal reached and will issue a new tick message.&amp;#160; The next time a WinForms event is not executing developer code a tick event is raised [1].&amp;#160; &lt;/p&gt;  &lt;p&gt;So imagine we had the following code.&amp;#160; &lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;Private Sub &lt;/span&gt;OnTimerTick() &lt;span style="color: blue"&gt;Handles &lt;/span&gt;m_timer.Tick
    RunSomeOperation()
&lt;span style="color: blue"&gt;End Sub&lt;/span&gt;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Consider what happens if RunSomeOperation takes longer than 2 seconds.&amp;#160; The Tick event is fired in real time so while we're in the middle of RunSomeOperation, another Tick event is being queued up for processing.&amp;#160; As soon as we leave OnTimerTick we're back in WinForms code which sees a Tick event and promptly raises it which puts us right back in OnTimerTick.&lt;/p&gt;

&lt;p&gt;This is contrary to what most people expect.&amp;#160; Most people expect the Tick event to fire 2 seconds after their code is finished executing.&amp;#160; &lt;/p&gt;

&lt;p&gt;To work around this developers should stop the timer when processing a timer event.&amp;#160; Just before exiting the event handler, re-enable the timer.&amp;#160; This will cause Windows to start calculating the interval from the start.&amp;#160; This has the effect of making the timer event fire 2 seconds after developer code stops executing.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;Private Sub &lt;/span&gt;OnTimerTick() &lt;span style="color: blue"&gt;Handles &lt;/span&gt;m_timer.Tick
    m_timer.Stop()
    &lt;span style="color: blue"&gt;Try
        &lt;/span&gt;RunSomeOperation()
    &lt;span style="color: blue"&gt;Finally
        &lt;/span&gt;m_timer.Start()
    &lt;span style="color: blue"&gt;End Try
End Sub&lt;/span&gt;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;[1] This is not 100% true.&amp;#160; It's really whenever the Application begins to pump messages again.&amp;#160; Message pumping, more specifically when it does and does not occur, is too involved for this discussion.&amp;#160; &lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9017488" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/jaredpar/archive/tags/VB/">VB</category><category domain="http://blogs.msdn.com/b/jaredpar/archive/tags/WinForms/">WinForms</category><category domain="http://blogs.msdn.com/b/jaredpar/archive/tags/Gotcha/">Gotcha</category></item><item><title>VB Catch ... When: Why so special?</title><link>http://blogs.msdn.com/b/jaredpar/archive/2008/10/09/vb-catch-when-why-so-special.aspx</link><pubDate>Thu, 09 Oct 2008 15:00:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:8990446</guid><dc:creator>JaredPar MSFT</dc:creator><slash:comments>5</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/jaredpar/rsscomments.aspx?WeblogPostID=8990446</wfw:commentRss><comments>http://blogs.msdn.com/b/jaredpar/archive/2008/10/09/vb-catch-when-why-so-special.aspx#comments</comments><description>&lt;P&gt;The VB Catch syntax has a particular feature not present in C#: When.&amp;nbsp; It allows users to filter expressions based on something other than their type.&amp;nbsp; Any arbitrary code can enter a When block to decide whether or not to handle an Exception&lt;/P&gt;&lt;PRE class=code&gt;    &lt;SPAN style="COLOR: blue"&gt;Sub &lt;/SPAN&gt;Sub1()
        &lt;SPAN style="COLOR: blue"&gt;Try
            &lt;/SPAN&gt;DoSomeAction()
        &lt;SPAN style="COLOR: blue"&gt;Catch &lt;/SPAN&gt;ex &lt;SPAN style="COLOR: blue"&gt;As &lt;/SPAN&gt;Exception &lt;SPAN style="COLOR: blue"&gt;When &lt;/SPAN&gt;Filter(ex)
            &lt;SPAN style="COLOR: blue"&gt;Stop
        End Try
    End Sub
&lt;/SPAN&gt;&lt;/PRE&gt;&lt;A href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"&gt;&lt;/A&gt;
&lt;P&gt;Newsgroups often ask, "Why's this so special? I could effectively get the same behavior out of C# by doing the following."&lt;/P&gt;&lt;PRE class=code&gt;&lt;SPAN style="COLOR: blue"&gt;static void &lt;/SPAN&gt;Sub1()
{
    &lt;SPAN style="COLOR: blue"&gt;try
    &lt;/SPAN&gt;{
        DoSomeAction();
    }
    &lt;SPAN style="COLOR: blue"&gt;catch &lt;/SPAN&gt;(&lt;SPAN style="COLOR: #2b91af"&gt;Exception &lt;/SPAN&gt;ex)
    {
        &lt;SPAN style="COLOR: blue"&gt;if &lt;/SPAN&gt;(Filter(ex))
        {
            &lt;SPAN style="COLOR: blue"&gt;throw&lt;/SPAN&gt;;
        }
        HandleException();
    }
}&lt;/PRE&gt;&lt;A href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"&gt;&lt;/A&gt;
&lt;P&gt;This is true to an extent.&amp;nbsp; In both cases the code is handling an exception and making a decision, via calling Filter, as to whether or not to handle the exception.&amp;nbsp; The subtle difference is when the Filter method is called.&amp;nbsp; &lt;/P&gt;
&lt;P&gt;In VB the When statement is actually implemented as an IL exception filter.&amp;nbsp; When an exception is thrown, exception filters are processed before the stack is unwound.&amp;nbsp; This means that if the Filter method created an error report that included the current stack trace, it would show the frame in which the exception occurred.&amp;nbsp; &lt;/P&gt;
&lt;P&gt;For example, in the code above if DoSomeAction() threw and the stack was examined in the Filter expression, the following stack would show up. &lt;/P&gt;
&lt;P&gt;&lt;A href="http://blogs.msdn.com/blogfiles/jaredpar/WindowsLiveWriter/VBCatch.WhenWhysospecial_1299E/image_2.png" mce_href="http://blogs.msdn.com/blogfiles/jaredpar/WindowsLiveWriter/VBCatch.WhenWhysospecial_1299E/image_2.png"&gt;&lt;IMG style="BORDER-BOTTOM: 0px; BORDER-LEFT: 0px; BORDER-TOP: 0px; BORDER-RIGHT: 0px" border=0 alt=image src="http://blogs.msdn.com/blogfiles/jaredpar/WindowsLiveWriter/VBCatch.WhenWhysospecial_1299E/image_thumb.png" width=504 height=304 mce_src="http://blogs.msdn.com/blogfiles/jaredpar/WindowsLiveWriter/VBCatch.WhenWhysospecial_1299E/image_thumb.png"&gt;&lt;/A&gt; &lt;/P&gt;
&lt;P&gt;Notice how the DoSomeAction method is clearly visible?&amp;nbsp; This is incredibly powerful for features like error reporting and investigation.&amp;nbsp; It also allows you to set powerful breakpoints where the exact state of the error can be examined and not just the post mortem.&amp;nbsp; &lt;/P&gt;
&lt;P&gt;Alternatively, code executed in the C# block will occur after the stack is unwound.&amp;nbsp; This gets rid of the culprit.&amp;nbsp; As long as your not in optimized code you can usually use the stack trace properties to get the source of the exception but you won't be able to examine the live state of the error. &lt;/P&gt;
&lt;P&gt;&lt;A href="http://blogs.msdn.com/blogfiles/jaredpar/WindowsLiveWriter/VBCatch.WhenWhysospecial_1299E/image_4.png" mce_href="http://blogs.msdn.com/blogfiles/jaredpar/WindowsLiveWriter/VBCatch.WhenWhysospecial_1299E/image_4.png"&gt;&lt;IMG style="BORDER-BOTTOM: 0px; BORDER-LEFT: 0px; BORDER-TOP: 0px; BORDER-RIGHT: 0px" border=0 alt=image src="http://blogs.msdn.com/blogfiles/jaredpar/WindowsLiveWriter/VBCatch.WhenWhysospecial_1299E/image_thumb_1.png" width=501 height=304 mce_src="http://blogs.msdn.com/blogfiles/jaredpar/WindowsLiveWriter/VBCatch.WhenWhysospecial_1299E/image_thumb_1.png"&gt;&lt;/A&gt;&lt;/P&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=8990446" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/jaredpar/archive/tags/VB/">VB</category><category domain="http://blogs.msdn.com/b/jaredpar/archive/tags/C_2300_/">C#</category></item><item><title>First MSDN article</title><link>http://blogs.msdn.com/b/jaredpar/archive/2008/08/18/first-msdn-article.aspx</link><pubDate>Mon, 18 Aug 2008 15:00:10 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:8848428</guid><dc:creator>JaredPar MSFT</dc:creator><slash:comments>2</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/jaredpar/rsscomments.aspx?WeblogPostID=8848428</wfw:commentRss><comments>http://blogs.msdn.com/b/jaredpar/archive/2008/08/18/first-msdn-article.aspx#comments</comments><description>&lt;p&gt;The August issue of MSDN magazine will be carrying an article I wrote this spring.&amp;#160; In it I toy around with using the deferred execution and lazy evaluation properties of LINQ to create more responsive UI code.&amp;#160; &lt;/p&gt;  &lt;p&gt;You can view the article &lt;a href="http://msdn.microsoft.com/en-us/magazine/cc721610.aspx"&gt;here&lt;/a&gt;.&amp;#160; &lt;/p&gt;  &lt;p&gt;As usual I appreciate any feedback you have.&amp;#160; &lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=8848428" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/jaredpar/archive/tags/VB/">VB</category><category domain="http://blogs.msdn.com/b/jaredpar/archive/tags/Misc/">Misc</category></item><item><title>Making Equality easier</title><link>http://blogs.msdn.com/b/jaredpar/archive/2008/06/03/making-equality-easier.aspx</link><pubDate>Tue, 03 Jun 2008 15:00:10 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:8569777</guid><dc:creator>JaredPar MSFT</dc:creator><slash:comments>2</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/jaredpar/rsscomments.aspx?WeblogPostID=8569777</wfw:commentRss><comments>http://blogs.msdn.com/b/jaredpar/archive/2008/06/03/making-equality-easier.aspx#comments</comments><description>&lt;p&gt;Recently I've done a bit of posting about the difficulties of &lt;a href="http://blogs.msdn.com/jaredpar/archive/2008/05/12/equality-isn-t-easy.aspx"&gt;properly implementing equality&lt;/a&gt; &lt;a href="http://blogs.msdn.com/jaredpar/archive/2008/04/28/properly-implementing-equality-in-vb.aspx"&gt;in VB&lt;/a&gt; (and DotNet in general).&amp;nbsp; While most of the problems can be fixed with a standard snippet the one really hard to implement issue is GetHashCode().&amp;nbsp; The rules for GetHashCode() are both simple and seemingly contradictory&lt;/p&gt; &lt;ol&gt; &lt;li&gt;If two objects are equal (via Equals) their GetHashCode() should be equal&lt;/li&gt; &lt;li&gt;GetHashCode() shouldn't ever change &lt;/li&gt;&lt;/ol&gt; &lt;p&gt;These rules imply that GetHashCode() is related to Equality.&amp;nbsp; At a fundamental level though GetHashCode has nothing to do with Equality.&amp;nbsp; Instead it is linked to bucketing and ultimately any hashing sturcture such as Dictionary, Hashtable, etc ...&amp;nbsp; &lt;/p&gt; &lt;p&gt;Unfortunately it is impossible to separate these two from an API perspective because it is ingrained into the BCL.&amp;nbsp; There is a way to separate this out at a functionality level and still satisfy all of the rules of the GetHashCode() and Equals()&lt;/p&gt;&lt;pre class="code"&gt;    &lt;span style="color: rgb(0,0,255)"&gt;Public&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Overrides&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Function&lt;/span&gt; GetHashCode() &lt;span style="color: rgb(0,0,255)"&gt;As&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Integer
&lt;/span&gt;        &lt;span style="color: rgb(0,0,255)"&gt;Return&lt;/span&gt; 1
    &lt;span style="color: rgb(0,0,255)"&gt;End&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Function&lt;/span&gt;&lt;/pre&gt;
&lt;p&gt;This absolutely maintains both of the rules for GetHashCode().&amp;nbsp; This allows you to completely separate Equality and GetHashCode() in your implementation while not breaking any BCL rules or assumptions. &lt;/p&gt;
&lt;p&gt;Of course this does come with a trade off.&amp;nbsp; As said before GetHashCode() is primarily used as a bucketing mechanism.&amp;nbsp; It will cause the performance of bucketing collections such as Dictionary or Hashtable to drop from close to O(1) to O(N).&amp;nbsp; But once again this is not a bug but a conscious trade off.&amp;nbsp; &lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=8569777" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/jaredpar/archive/tags/VB/">VB</category><category domain="http://blogs.msdn.com/b/jaredpar/archive/tags/Patterns/">Patterns</category></item><item><title>Equality isn't easy</title><link>http://blogs.msdn.com/b/jaredpar/archive/2008/05/12/equality-isn-t-easy.aspx</link><pubDate>Mon, 12 May 2008 15:00:20 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:8480384</guid><dc:creator>JaredPar MSFT</dc:creator><slash:comments>1</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/jaredpar/rsscomments.aspx?WeblogPostID=8480384</wfw:commentRss><comments>http://blogs.msdn.com/b/jaredpar/archive/2008/05/12/equality-isn-t-easy.aspx#comments</comments><description>&lt;p&gt;After my recent postings on the &lt;a href="http://blogs.msdn.com/jaredpar/archive/2008/04/28/properly-implementing-equality-in-vb.aspx"&gt;rules of Equality&lt;/a&gt;, I thought it would be a good idea to post a simple example of equality.&amp;nbsp; The class in question, Example, has only one field of type Integer name m_field1.&amp;nbsp; Two instances of Example are equal if m_field1 has the same value.&amp;nbsp; So the real equality check is just a single Integer comparison.&amp;nbsp; &lt;/p&gt; &lt;p&gt;Unfortunately, as my posts alluded to, even though the check is simple getting it right is not necessarily so.&amp;nbsp; The equality portion of example takes roughly 20 lines of code while the actual equality check represents only 1 of those lines [1].&amp;nbsp; Not a good ratio.&amp;nbsp; The good and bad news about the other 19 lines is they are boiler plate so once you know them you don't have to think about them.&amp;nbsp; For my own purposes I've converted those 19 lines into a snippet which automates the process but doesn't make it any easier on the eye. &lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: rgb(0,0,255)"&gt;Class&lt;/span&gt; Example
    &lt;span style="color: rgb(0,0,255)"&gt;Implements&lt;/span&gt; IEquatable(&lt;span style="color: rgb(0,0,255)"&gt;Of&lt;/span&gt; Example)

    &lt;span style="color: rgb(0,0,255)"&gt;Private&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;ReadOnly&lt;/span&gt; m_field1 &lt;span style="color: rgb(0,0,255)"&gt;As&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Integer
&lt;/span&gt;    &lt;span style="color: rgb(0,0,255)"&gt;Public&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Sub&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;New&lt;/span&gt;(&lt;span style="color: rgb(0,0,255)"&gt;ByVal&lt;/span&gt; field &lt;span style="color: rgb(0,0,255)"&gt;As&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Integer&lt;/span&gt;)
        m_field1 = field
    &lt;span style="color: rgb(0,0,255)"&gt;End&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Sub

&lt;/span&gt;    &lt;span style="color: rgb(0,0,255)"&gt;Public&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Function&lt;/span&gt; Equals1(&lt;span style="color: rgb(0,0,255)"&gt;ByVal&lt;/span&gt; other &lt;span style="color: rgb(0,0,255)"&gt;As&lt;/span&gt; Example) &lt;span style="color: rgb(0,0,255)"&gt;As&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Boolean&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Implements&lt;/span&gt; System.IEquatable(&lt;span style="color: rgb(0,0,255)"&gt;Of&lt;/span&gt; Example).Equals
        &lt;span style="color: rgb(0,0,255)"&gt;If&lt;/span&gt; other &lt;span style="color: rgb(0,0,255)"&gt;Is&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Nothing&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Then
&lt;/span&gt;            &lt;span style="color: rgb(0,0,255)"&gt;Return&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;False
&lt;/span&gt;        &lt;span style="color: rgb(0,0,255)"&gt;End&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;If

&lt;/span&gt;        &lt;span style="color: rgb(0,0,255)"&gt;Return&lt;/span&gt; m_field1 = other.m_field1
    &lt;span style="color: rgb(0,0,255)"&gt;End&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Function

&lt;/span&gt;    &lt;span style="color: rgb(0,0,255)"&gt;Public&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Overrides&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Function&lt;/span&gt; Equals(&lt;span style="color: rgb(0,0,255)"&gt;ByVal&lt;/span&gt; obj &lt;span style="color: rgb(0,0,255)"&gt;As&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Object&lt;/span&gt;) &lt;span style="color: rgb(0,0,255)"&gt;As&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Boolean
&lt;/span&gt;        &lt;span style="color: rgb(0,0,255)"&gt;Return&lt;/span&gt; Equals1(&lt;span style="color: rgb(0,0,255)"&gt;TryCast&lt;/span&gt;(obj, Example))
    &lt;span style="color: rgb(0,0,255)"&gt;End&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Function

&lt;/span&gt;    &lt;span style="color: rgb(0,0,255)"&gt;Public&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Overrides&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Function&lt;/span&gt; GetHashCode() &lt;span style="color: rgb(0,0,255)"&gt;As&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Integer
&lt;/span&gt;        &lt;span style="color: rgb(0,0,255)"&gt;Return&lt;/span&gt; m_field1.GetHashCode
    &lt;span style="color: rgb(0,0,255)"&gt;End&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Function

&lt;/span&gt;    &lt;span style="color: rgb(0,0,255)"&gt;Public&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Shared&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Operator&lt;/span&gt; =(&lt;span style="color: rgb(0,0,255)"&gt;ByVal&lt;/span&gt; left &lt;span style="color: rgb(0,0,255)"&gt;As&lt;/span&gt; Example, &lt;span style="color: rgb(0,0,255)"&gt;ByVal&lt;/span&gt; right &lt;span style="color: rgb(0,0,255)"&gt;As&lt;/span&gt; Example) &lt;span style="color: rgb(0,0,255)"&gt;As&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Boolean
&lt;/span&gt;        &lt;span style="color: rgb(0,0,255)"&gt;Return&lt;/span&gt; EqualityComparer(&lt;span style="color: rgb(0,0,255)"&gt;Of&lt;/span&gt; Example).Default.Equals(left, right)
    &lt;span style="color: rgb(0,0,255)"&gt;End&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Operator

&lt;/span&gt;    &lt;span style="color: rgb(0,0,255)"&gt;Public&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Shared&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Operator&lt;/span&gt; &amp;lt;&amp;gt;(&lt;span style="color: rgb(0,0,255)"&gt;ByVal&lt;/span&gt; left &lt;span style="color: rgb(0,0,255)"&gt;As&lt;/span&gt; Example, &lt;span style="color: rgb(0,0,255)"&gt;ByVal&lt;/span&gt; right &lt;span style="color: rgb(0,0,255)"&gt;As&lt;/span&gt; Example) &lt;span style="color: rgb(0,0,255)"&gt;As&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Boolean
&lt;/span&gt;        &lt;span style="color: rgb(0,0,255)"&gt;Return&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Not&lt;/span&gt; EqualityComparer(&lt;span style="color: rgb(0,0,255)"&gt;Of&lt;/span&gt; Example).Default.Equals(left, right)
    &lt;span style="color: rgb(0,0,255)"&gt;End&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Operator

End&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Class

Module&lt;/span&gt; Module1

    &lt;span style="color: rgb(0,0,255)"&gt;Sub&lt;/span&gt; AssertTrue(&lt;span style="color: rgb(0,0,255)"&gt;ByVal&lt;/span&gt; cond &lt;span style="color: rgb(0,0,255)"&gt;As&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Boolean&lt;/span&gt;)
        Debug.Assert(cond, &lt;span style="color: rgb(163,21,21)"&gt;"failure"&lt;/span&gt;)
    &lt;span style="color: rgb(0,0,255)"&gt;End&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Sub

&lt;/span&gt;    &lt;span style="color: rgb(0,0,255)"&gt;Sub&lt;/span&gt; AssertFalse(&lt;span style="color: rgb(0,0,255)"&gt;ByVal&lt;/span&gt; cond &lt;span style="color: rgb(0,0,255)"&gt;As&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Boolean&lt;/span&gt;)
        Debug.Assert(&lt;span style="color: rgb(0,0,255)"&gt;Not&lt;/span&gt; cond, &lt;span style="color: rgb(163,21,21)"&gt;"failure"&lt;/span&gt;)
    &lt;span style="color: rgb(0,0,255)"&gt;End&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Sub

&lt;/span&gt;    &lt;span style="color: rgb(0,0,255)"&gt;Sub&lt;/span&gt; Main()
        &lt;span style="color: rgb(0,0,255)"&gt;Dim&lt;/span&gt; v1 &lt;span style="color: rgb(0,0,255)"&gt;As&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;New&lt;/span&gt; Example(1)
        &lt;span style="color: rgb(0,0,255)"&gt;Dim&lt;/span&gt; v2 &lt;span style="color: rgb(0,0,255)"&gt;As&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;New&lt;/span&gt; Example(2)
        &lt;span style="color: rgb(0,0,255)"&gt;Dim&lt;/span&gt; v3 &lt;span style="color: rgb(0,0,255)"&gt;As&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;New&lt;/span&gt; Example(1)

        AssertFalse(v1 &lt;span style="color: rgb(0,0,255)"&gt;Is&lt;/span&gt; v2)
        AssertFalse(v1 &lt;span style="color: rgb(0,0,255)"&gt;Is&lt;/span&gt; v3)
        AssertTrue(v1 &lt;span style="color: rgb(0,0,255)"&gt;Is&lt;/span&gt; v1)
        AssertFalse(v1 = v2)
        AssertTrue(v1 = v3)
        AssertFalse(v1 = &lt;span style="color: rgb(0,0,255)"&gt;Nothing&lt;/span&gt;)
        AssertFalse(&lt;span style="color: rgb(0,0,255)"&gt;Nothing&lt;/span&gt; = v1)
        AssertTrue(v1 &amp;lt;&amp;gt; v2)
        AssertTrue(v1 &amp;lt;&amp;gt; &lt;span style="color: rgb(0,0,255)"&gt;Nothing&lt;/span&gt;)
        AssertTrue(EqualityComparer(&lt;span style="color: rgb(0,0,255)"&gt;Of&lt;/span&gt; Example).Default.Equals(v1, v3))
        AssertFalse(EqualityComparer(&lt;span style="color: rgb(0,0,255)"&gt;Of&lt;/span&gt; Example).Default.Equals(v1, v2))
    &lt;span style="color: rgb(0,0,255)"&gt;End&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Sub

End&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Module
&lt;/span&gt;&lt;/pre&gt;
&lt;p&gt;[1] Before VB criticism enters, C# has roughly the same ratio for the same sample.&amp;nbsp; &lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=8480384" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/jaredpar/archive/tags/VB/">VB</category></item><item><title>IEquatable(Of T) and GetHashCode()</title><link>http://blogs.msdn.com/b/jaredpar/archive/2008/05/09/iequatable-of-t-and-gethashcode.aspx</link><pubDate>Fri, 09 May 2008 15:00:53 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:8473844</guid><dc:creator>JaredPar MSFT</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/jaredpar/rsscomments.aspx?WeblogPostID=8473844</wfw:commentRss><comments>http://blogs.msdn.com/b/jaredpar/archive/2008/05/09/iequatable-of-t-and-gethashcode.aspx#comments</comments><description>&lt;p&gt;This is a bit of a follow up to a &lt;a href="http://blogs.msdn.com/jaredpar/archive/2008/04/28/properly-implementing-equality-in-vb.aspx"&gt;previous post&lt;/a&gt; we discussed how to properly implement equality in VB.&amp;nbsp; Several users commented/asked that &lt;a href="http://msdn.microsoft.com/en-us/library/ms131187(VS.80).aspx"&gt;IEquatable(Of T)&lt;/a&gt; could be used in place of overriding Equals().&amp;nbsp; Since &lt;a href="http://msdn.microsoft.com/en-us/library/ms131187(VS.80).aspx"&gt;IEquatable(Of T)&lt;/a&gt;&amp;nbsp; doesn't define a GetHashCode() method the user didn't need to define it and hence run into all of the problems associated with GetHashCode() usage.&amp;nbsp; &lt;/p&gt; &lt;p&gt;Unfortunately this is not the case.&amp;nbsp; Several parts of the framework link IEquatable(Of T).Equals and Object.GetHashCode() in the same way that Object.Equals() and Object.GetHashCode() are linked. &lt;/p&gt; &lt;p&gt;The prime example of this is &lt;a href="http://msdn.microsoft.com/en-us/library/ms132123.aspx"&gt;EqualityComparer(Of T)&lt;/a&gt;.&amp;nbsp; This class is used to provide instances of IEqualityComparer(Of T) for any given type.&amp;nbsp; Under the hood it tries to determine the best way checking for equality in types.&amp;nbsp; If T implements IEquatable(Of T) it will eventually create an instance of GenericEqualityComparer(Of T) [1].&amp;nbsp; The methods of IEqualityComparer(Of T) are implemented as follows (boundary cases removed)&lt;/p&gt; &lt;ul&gt; &lt;li&gt;Equals(left, right): return left.Equals(right) &lt;/li&gt; &lt;ul&gt; &lt;li&gt;Equals in this case is IEquatable(Of T).Equals&lt;/li&gt;&lt;/ul&gt; &lt;li&gt;GetHashCode(obj): return obj.GetHashCode()&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;This implicitly links IEquatable(Of T).Equals to Object.GetHashCode().&amp;nbsp; Therefore if you implement IEquatable(Of T) you should also override GetHashCode().&amp;nbsp; The best way to view this is "if you implement IEquatable(Of T) you should override Equals and GetHashCode."&lt;/p&gt; &lt;p&gt;What's even more unfortunate is there is no feedback to indicate this relationship exists.&amp;nbsp; If you override Equals or GetHashCode both the C# and VB compilers will issue a warning/error.&amp;nbsp; Implementing IEquatable(Of T) produces no such warning.&amp;nbsp; &lt;/p&gt; &lt;p&gt;[1] Unfortunately this is a private type so you will need to use Reflector to view the type.&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=8473844" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/jaredpar/archive/tags/VB/">VB</category><category domain="http://blogs.msdn.com/b/jaredpar/archive/tags/Patterns/">Patterns</category></item><item><title>Properly Implementing Equality in VB</title><link>http://blogs.msdn.com/b/jaredpar/archive/2008/04/28/properly-implementing-equality-in-vb.aspx</link><pubDate>Mon, 28 Apr 2008 15:04:06 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:8428051</guid><dc:creator>JaredPar MSFT</dc:creator><slash:comments>6</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/jaredpar/rsscomments.aspx?WeblogPostID=8428051</wfw:commentRss><comments>http://blogs.msdn.com/b/jaredpar/archive/2008/04/28/properly-implementing-equality-in-vb.aspx#comments</comments><description>&lt;p&gt;Many developers want to implement equality functions for their objects.&amp;#160; DotNet made equality a deep part of the framework and added support all the way up to System.Object with &lt;a href="http://msdn2.microsoft.com/en-us/library/bsc2ak47.aspx"&gt;Equals&lt;/a&gt; and &lt;a href="http://msdn2.microsoft.com/en-us/library/system.object.gethashcode.aspx"&gt;GetHashCode&lt;/a&gt;.&amp;#160;&amp;#160; In addition to the strongly enforced method semantics of GetHashCode and Equals there are also several other hard to enforce patterns that developers must follow in order to properly integrate into the rest of the DotNet framework.&amp;#160; We'll explore those rules today. &lt;/p&gt;  &lt;p&gt;Before even talking about how to implement equality we need to define the types of equality.&amp;#160; &lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Reference equality: Are these two objects really the exact same object.&amp;#160; &lt;/li&gt;    &lt;li&gt;Object/value equality: Depends on what the object author thinks equality means.&amp;#160; Can be anything from reference equality up to, comparing fields, to were they created in the same app domain. &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;In VB these are two very separate types of equality.&amp;#160; Reference equality is expressed through the &lt;a href="http://msdn2.microsoft.com/en-us/library/kb136x1y(VS.80).aspx"&gt;&amp;quot;Is&amp;quot;&lt;/a&gt; operator.&amp;#160; Object equality is done directly through operator=, operator&amp;lt;&amp;gt; and Equals.&amp;#160; This is also indirectly exposed via GetHashCode, EqualityComparer(Of T) and other framework patterns.&lt;/p&gt;  &lt;p&gt;When implementing object/value Equality there are four methods that are important to consider in order to fit expected patterns.&amp;#160; What's even more important is understanding which ones must be implemented together.&amp;#160; If an author overrides any of the functions in the following pairs they &lt;strong&gt;must &lt;/strong&gt;override both.&amp;#160; &lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Equals/GetHashCode&lt;/li&gt;    &lt;li&gt;Operator=/Operator!=&lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;To make it easier, my rule of thumb is to override all four or none.&lt;/p&gt;  &lt;h3&gt;Equals&lt;/h3&gt;  &lt;p&gt;This is the bread and butter of object/value equality.&amp;#160; The author has free reign to decide what is and what is not equal.&amp;#160; However there are a few rules authors must follow in order to fit into the rest of the framework. &lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;Do not throw an exception from Equals.&amp;#160; Many components call Equals in a loop and there is no way for them to handle or recover from an exception.&amp;#160; If the object is not equal just return False &lt;/li&gt;    &lt;li&gt;The object passed in is typed to object.&amp;#160; It is perfectly valid for the framework to pass in an object that is completely unrelated to the type defining Equals.&amp;#160; The type author must account for and handle this case. &lt;/li&gt;    &lt;li&gt;The framework can pass in Nothing as a parameter to Equals and this is valid.&amp;#160; &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;#2 and #3 may seem a bit off at first but it is implemented with a standard pattern as seen below. &lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;Class &lt;/span&gt;C1
    &lt;span style="color: blue"&gt;Public Overrides Function &lt;/span&gt;Equals(&lt;span style="color: blue"&gt;ByVal &lt;/span&gt;obj &lt;span style="color: blue"&gt;As Object&lt;/span&gt;) &lt;span style="color: blue"&gt;As Boolean
        Dim &lt;/span&gt;other = &lt;span style="color: blue"&gt;TryCast&lt;/span&gt;(obj, C1)
        &lt;span style="color: blue"&gt;If &lt;/span&gt;other &lt;span style="color: blue"&gt;Is Nothing Then
            Return False
        End If
        &lt;/span&gt;...
    &lt;span style="color: blue"&gt;End Function
End Class&lt;/span&gt;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;It's very important that you use &amp;quot;Is&amp;quot; to compare other in the above example.&amp;#160; Imagine if you slip up and type &amp;quot;=&amp;quot; instead.&amp;#160; You're about to override Operator= and this will cause &amp;quot;other=Nothing&amp;quot; to call operator=.&amp;#160; If this is a valid C1 instance operator= will almost certainly call Equals and then you'd have a stack overflow.&amp;#160; Our implementation of Operator= below will avoid this problem.&lt;/p&gt;

&lt;h3&gt;GetHashCode&lt;/h3&gt;

&lt;p&gt;This is both the easiest and trickiest function to override because it has very subtle semantics which cause very hard to find bugs in code.&amp;#160; The simple rule is &amp;quot;If two objects are equal in the sense of value equality they must return the same value in GetHashCode()&amp;quot;.&amp;#160; &lt;/p&gt;

&lt;p&gt;Why?&amp;#160; Many classes use the hash code to classify an object.&amp;#160; In particular hash tables and dictionaries tend to place objects in buckets based on their hash code.&amp;#160; When checking if an object is already in the hash table it will first look for it in a bucket.&amp;#160; If two objects are equal but have different hash codes they may be put into different buckets and the dictionary would fail to lookup the object.&lt;/p&gt;

&lt;p&gt;The better version of the GetHashCode rule has a small suffix on the simple rule.&amp;#160; &amp;quot;Only calculate the hash code based off of primitive fields which are ReadOnly&amp;quot;. This is not an absolute requirement as long as you are careful when you are code.&amp;#160; But as &lt;a href="http://blogs.msdn.com/jaredpar/archive/2008/03/24/part-of-being-a-good-programmer-is-learning-not-to-trust-yourself.aspx"&gt;previously stated&lt;/a&gt;, when coding it's best not to trust yourself to do the right thing.&amp;#160; Not doing this will get you into trouble when dealing with Hashtables and dictionaries.&amp;#160; &lt;/p&gt;

&lt;p&gt;For instance take this not so small example.&amp;#160; In this case value equality is based solely off of Field1 which is a modifiable field.&amp;#160; Once Field1 is changed you may or may not be able to access the value in the dictionary because GetHashCode() will change.&amp;#160; This example is contrived but it does happen in the real world and it can be incredibly difficult to track down.&amp;#160; &lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;Class &lt;/span&gt;C2
    &lt;span style="color: blue"&gt;Public &lt;/span&gt;Field1 &lt;span style="color: blue"&gt;As Integer

    Public Sub New&lt;/span&gt;(&lt;span style="color: blue"&gt;ByVal &lt;/span&gt;f1 &lt;span style="color: blue"&gt;As Integer&lt;/span&gt;)
        Field1 = f1
    &lt;span style="color: blue"&gt;End Sub
    Public Overrides Function &lt;/span&gt;GetHashCode() &lt;span style="color: blue"&gt;As Integer
        Return &lt;/span&gt;Field1.GetHashCode()
    &lt;span style="color: blue"&gt;End Function
    Public Overrides Function &lt;/span&gt;Equals(&lt;span style="color: blue"&gt;ByVal &lt;/span&gt;obj &lt;span style="color: blue"&gt;As Object&lt;/span&gt;) &lt;span style="color: blue"&gt;As Boolean
        Dim &lt;/span&gt;other = &lt;span style="color: blue"&gt;TryCast&lt;/span&gt;(obj, C2)
        &lt;span style="color: blue"&gt;If &lt;/span&gt;other &lt;span style="color: blue"&gt;Is Nothing Then
            Return False
        End If
        Return &lt;/span&gt;other.Field1 = Field1
    &lt;span style="color: blue"&gt;End Function
End Class

Module &lt;/span&gt;Module1

    &lt;span style="color: blue"&gt;Sub &lt;/span&gt;Main()
        &lt;span style="color: blue"&gt;Dim &lt;/span&gt;map = &lt;span style="color: blue"&gt;New &lt;/span&gt;Dictionary(&lt;span style="color: blue"&gt;Of &lt;/span&gt;C2, &lt;span style="color: blue"&gt;String&lt;/span&gt;)
        &lt;span style="color: blue"&gt;Dim &lt;/span&gt;v1 = &lt;span style="color: blue"&gt;New &lt;/span&gt;C2(44)
        map.Add(v1, &lt;span style="color: #a31515"&gt;&amp;quot;avalue&amp;quot;&lt;/span&gt;)
        Console.WriteLine(map(v1))
        v1.Field1 = 2
        Console.WriteLine(map(v1))  &lt;span style="color: green"&gt;' Potentially throws
    &lt;/span&gt;&lt;span style="color: blue"&gt;End Sub

End Module
&lt;/span&gt;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;If Field1 were ReadOnly there would be no way to hit this problem.&amp;#160; Then again we'd also not be able to change Field1.&amp;#160; &lt;/p&gt;

&lt;h3&gt;Operator=&lt;/h3&gt;

&lt;p&gt;When implementing equality overriding operator= allows you to use the more pleasant and reliable version of syntax comparison: a=b vs. a.Equals(b).&amp;#160; I say more reliable because using a.Equals(b) has an inherent dependency on &amp;quot;a&amp;quot; being a non-Nothing object.&amp;#160; &amp;quot;Operator=&amp;quot; makes no assumption and should operate correctly in the presence of Nothing.&lt;/p&gt;

&lt;p&gt;Operator= has virtually the same rules as Equals.&amp;#160; Mainly don't throw from operator=.&amp;#160; Operator= is usually just defined in terms of Equals() and since it also has to respect the no throw rule once we get there we are in good shape.&amp;#160; Getting to Equals() can be tricky though because one or both of the arguments can be Nothing.&amp;#160; In addition make sure not to use &amp;quot;=&amp;quot; to check for Nothing because you're back to the stack overflow problem.&amp;#160; &lt;/p&gt;

&lt;p&gt;What's great here is there is a simple solution that you should use every time you define Operator=.&amp;#160; &lt;a href="http://msdn2.microsoft.com/en-us/library/ms132123.aspx"&gt;EqualityComparer(Of T)&lt;/a&gt; knows all of these rules and in the face of both parameters being non-Nothing will call Equals() just like we want.&amp;#160; This makes the definition of Operator= boiler plate (I define very Operator= the exact same way)&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;Public Shared Operator &lt;/span&gt;=(&lt;span style="color: blue"&gt;ByVal &lt;/span&gt;left &lt;span style="color: blue"&gt;As &lt;/span&gt;C2, &lt;span style="color: blue"&gt;ByVal &lt;/span&gt;right &lt;span style="color: blue"&gt;As &lt;/span&gt;C2) &lt;span style="color: blue"&gt;As Boolean
    Return &lt;/span&gt;EqualityComparer(&lt;span style="color: blue"&gt;Of &lt;/span&gt;C2).Default.Equals(left, right)
&lt;span style="color: blue"&gt;End Operator&lt;/span&gt;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;What's even better is that EqualityComparer(Of T) understands the stack overflow problem which can occur in equality comparison and avoids it.&amp;#160; &lt;/p&gt;

&lt;h3&gt;Operator &amp;lt;&amp;gt;&lt;/h3&gt;

&lt;p&gt;Operator&amp;lt;&amp;gt; has the same rules as Operator= and luckily the same easy type of answer.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;Public Shared Operator &lt;/span&gt;&amp;lt;&amp;gt;(&lt;span style="color: blue"&gt;ByVal &lt;/span&gt;left &lt;span style="color: blue"&gt;As &lt;/span&gt;C2, &lt;span style="color: blue"&gt;ByVal &lt;/span&gt;right &lt;span style="color: blue"&gt;As &lt;/span&gt;C2) &lt;span style="color: blue"&gt;As Boolean
    Return Not &lt;/span&gt;EqualityComparer(&lt;span style="color: blue"&gt;Of &lt;/span&gt;C2).Default.Equals(left, right)
&lt;span style="color: blue"&gt;End Operator&lt;/span&gt;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;h3&gt;Wrapping Up&lt;/h3&gt;

&lt;p&gt;I started this article thinking it would be a few paragraphs of simple rules.&amp;#160; But as I kept going I kept remembering the subtleties and problems I encountered in the past.&amp;#160; &lt;/p&gt;

&lt;p&gt;For my own projects I avoid implementing equality unless it's truly needed because of the problems with properly implementing GetHashCode().&amp;#160; The one exception is when I define immutable objects.&amp;#160; Immutable objects have no problems with GetHashCode() since they are unchangable so Equality is straight forward.&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=8428051" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/jaredpar/archive/tags/VB/">VB</category><category domain="http://blogs.msdn.com/b/jaredpar/archive/tags/Patterns/">Patterns</category></item><item><title>Me, MyBase, MyClass and MyPost on the subject</title><link>http://blogs.msdn.com/b/jaredpar/archive/2008/04/25/me-mybase-myclass-and-mypost-on-the-subject.aspx</link><pubDate>Fri, 25 Apr 2008 18:09:08 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:8424213</guid><dc:creator>JaredPar MSFT</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/jaredpar/rsscomments.aspx?WeblogPostID=8424213</wfw:commentRss><comments>http://blogs.msdn.com/b/jaredpar/archive/2008/04/25/me-mybase-myclass-and-mypost-on-the-subject.aspx#comments</comments><description>&lt;p&gt;Recently we had a good discussion on an internal alias about the use of Me, MyClass and MyBase in VB.&amp;nbsp; Me, MyBase and MyClass are all ways to access instance member data in a VB class or structure.&amp;nbsp; There was a little bit of confusion on the actual workings and meanings of the keywords in various contexts and I want to use this post to shed light on the different meanings. &lt;/p&gt; &lt;h3&gt;The Basics&lt;/h3&gt; &lt;p&gt;The keywords are used to alter the way in which instance members of a class/structure are accessed.&amp;nbsp; In particular they affect the way Overridable/MustOverride/Overrides functions are evaluated. Methods defined with Overridable/Overrides/MustOverride are defined as virtual by the CLR.&amp;nbsp; For the purpose of this post all of these definitions are mostly equal.&amp;nbsp; This discussion will be useless without and example so here's the code to discuss.&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;Class &lt;/span&gt;GrandParent
    &lt;span style="color: blue"&gt;Public Overridable Sub &lt;/span&gt;Sub1()
        Console.WriteLine(&lt;span style="color: #a31515"&gt;"GrandParent.Sub1"&lt;/span&gt;)
    &lt;span style="color: blue"&gt;End Sub
End Class

Class &lt;/span&gt;Parent
    &lt;span style="color: blue"&gt;Inherits &lt;/span&gt;GrandParent
    &lt;span style="color: blue"&gt;Public Overrides Sub &lt;/span&gt;Sub1()
        Console.WriteLine(&lt;span style="color: #a31515"&gt;"Parent.Sub1"&lt;/span&gt;)
    &lt;span style="color: blue"&gt;End Sub
End Class

Class &lt;/span&gt;Child
    &lt;span style="color: blue"&gt;Inherits &lt;/span&gt;Parent
    &lt;span style="color: blue"&gt;Public Overrides Sub &lt;/span&gt;Sub1()
        Console.WriteLine(&lt;span style="color: #a31515"&gt;"Child.Sub1"&lt;/span&gt;)
    &lt;span style="color: blue"&gt;End Sub
End Class&lt;/span&gt;&lt;/pre&gt;
&lt;p&gt;In this case Sub1 is a virtual method and there are three instances of it (one per class).&amp;nbsp; By default virtual methods are called based on the runtime type of the object.&amp;nbsp; The CLR will essentially walk the hierarchy from current type to object looking for the first class which defines a particular method and call that version.&amp;nbsp; It doesn't matter what the variable type is declared as, just what type it actually is.&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;Dim &lt;/span&gt;v1 &lt;span style="color: blue"&gt;As &lt;/span&gt;GrandParent = &lt;span style="color: blue"&gt;New &lt;/span&gt;Parent
v1.Sub1()   &lt;span style="color: green"&gt;' Calls Parent.Sub1
&lt;/span&gt;&lt;span style="color: blue"&gt;Dim &lt;/span&gt;v2 &lt;span style="color: blue"&gt;As &lt;/span&gt;GrandParent = &lt;span style="color: blue"&gt;New &lt;/span&gt;GrandParent
v2.Sub1()   &lt;span style="color: green"&gt;' Calls GrandParent.Sub1&lt;/span&gt;&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;h3&gt;Changing the call&lt;/h3&gt;
&lt;p&gt;If the CLR will always call a virtual Sub/Function based on the runtime type of an object how can I access the parent function?&amp;nbsp; This is where MyBase comes in.&amp;nbsp; MyBase allows you to call the version of the virtual method defined in the parent class.&amp;nbsp; Essentially it tells the CLR call this method/property as if my runtime type was my base type.&amp;nbsp; &lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;Class &lt;/span&gt;Child2
    &lt;span style="color: blue"&gt;Inherits &lt;/span&gt;Parent
    &lt;span style="color: blue"&gt;Public Overrides Sub &lt;/span&gt;Sub1()
        &lt;span style="color: blue"&gt;MyBase&lt;/span&gt;.Sub1()   &lt;span style="color: green"&gt;' Calls Parent.Sub1
        &lt;/span&gt;Console.WriteLine(&lt;span style="color: #a31515"&gt;"Child2.Sub1"&lt;/span&gt;)
    &lt;span style="color: blue"&gt;End Sub
End Class
&lt;/span&gt;&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;MyClass is similar to MyBase.&amp;nbsp; Instead of telling the CLR the current type is the base type, it tells the CLR the runtime type is the type where MyClass is used.&amp;nbsp; This allows developers to call their type's version of a virtual method no matter who derives from them.&amp;nbsp; In the following example it doesn't matter how many, or who derives from Child3, Sub2 will always call the version of Sub1 defined in Child3.&lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;Class &lt;/span&gt;Child3
    &lt;span style="color: blue"&gt;Inherits &lt;/span&gt;Parent
    &lt;span style="color: blue"&gt;Public Overrides Sub &lt;/span&gt;Sub1()
        Console.WriteLine(&lt;span style="color: #a31515"&gt;"Child3.Sub1"&lt;/span&gt;)
    &lt;span style="color: blue"&gt;End Sub
    Public Sub &lt;/span&gt;Sub2()
        &lt;span style="color: blue"&gt;MyClass&lt;/span&gt;.Sub1()
    &lt;span style="color: blue"&gt;End Sub
End Class&lt;/span&gt;&lt;/pre&gt;
&lt;h3&gt;So, why not MyChild?&lt;/h3&gt;
&lt;p&gt;The short answer is, it's not verifiable.&amp;nbsp; When writing MyBase we can verify that indeed there is a sub/function/property matching the call site in the base class.&amp;nbsp; If no such method exists it will result in an error.&amp;nbsp; MyClass is similarly easy to verify.&amp;nbsp; With MyChild however there would be no useful way of guaranteeing a particular sub/function/property was defined on the child class.&amp;nbsp; &lt;/p&gt;
&lt;p&gt;One way you can verify a child class contains a particular property/sub/function is to make it MustOverride.&amp;nbsp; However in this case there is no actual definition in the original type.&amp;nbsp; In fact, if you try and access a MustOverride method with MyClass it will generate a compile time error. Therefore every call must at least occur in the child class or lower rendering MyChild superfluous.&lt;/p&gt;
&lt;h3&gt;What about non-virtual methods and properties?&lt;/h3&gt;
&lt;p&gt;The primary intent of MyBase/MyClass is to call virtual methods in a non-virtual way.&amp;nbsp; However they can also be used to call non-virtual methods.&amp;nbsp; From the perspective of the user calling a non-virtual method with MyBase/MyClass/Me has no discernable difference.&amp;nbsp; If you crack open the generated IL you can see a small difference in the op code but the short story is it won't affect your program.&amp;nbsp; &lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=8424213" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/jaredpar/archive/tags/VB/">VB</category></item><item><title>BinaryInsert Part2</title><link>http://blogs.msdn.com/b/jaredpar/archive/2008/04/07/binaryinsert-part2.aspx</link><pubDate>Mon, 07 Apr 2008 22:09:36 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:8349083</guid><dc:creator>JaredPar MSFT</dc:creator><slash:comments>7</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/jaredpar/rsscomments.aspx?WeblogPostID=8349083</wfw:commentRss><comments>http://blogs.msdn.com/b/jaredpar/archive/2008/04/07/binaryinsert-part2.aspx#comments</comments><description>&lt;p&gt;&lt;a href="http://blogs.msdn.com/jaredpar/archive/2008/03/31/missing-api-list-of-t-binaryinsert.aspx"&gt;Previously&lt;/a&gt; I discussed a potential missing API in List(Of T).BinaryInsert.&amp;nbsp; One of the items I mentioned was it had better performance because it was O(Log N) vs Insert and Sort which is O(NLogN).&amp;nbsp; Several users correctly pointed out this was incorrect and that Insert() had the additional overhead of an Array.Copy() which is O(N)ish.&amp;nbsp; But most agreed O(N) + O(LogN) was better than O(NLogN).&amp;nbsp; &lt;/p&gt; &lt;p&gt;Given that I already missed a key portion, I decided to write a test program to try out the various methods.&amp;nbsp; Caveat: I'm not a performance guy.&amp;nbsp; While I find performance intriguing and interesting it is by no means my specialty.&amp;nbsp; Any single performance test is unlikely to capture all real world scenarios.&amp;nbsp; However I did find the results a bit surprising.&amp;nbsp; At the bottom of the post is the test code I wrote.&amp;nbsp; &lt;/p&gt; &lt;p&gt;Here is the summary output.&amp;nbsp; &lt;/p&gt; &lt;blockquote&gt; &lt;p&gt;Force Jit&lt;br&gt;BinaryInsert:&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; 00:00:00.0051167&lt;br&gt;Insert Then Sort: 00:00:00.0000251&lt;br&gt;Range (0-99)&lt;br&gt;BinaryInsert:&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; 00:00:00.0000266&lt;br&gt;Insert Then Sort: 00:00:00.0000316&lt;br&gt;Random 10&lt;br&gt;BinaryInsert:&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; 00:00:00.0000053&lt;br&gt;Insert Then Sort: 00:00:00.0000034&lt;br&gt;Random 100&lt;br&gt;BinaryInsert:&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; 00:00:00.0000294&lt;br&gt;Insert Then Sort: 00:00:00.0000235&lt;br&gt;Random 1000&lt;br&gt;BinaryInsert:&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; 00:00:00.0004917&lt;br&gt;Insert Then Sort: 00:00:00.0001526&lt;br&gt;Random 10000&lt;br&gt;BinaryInsert:&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; 00:00:00.0261899&lt;br&gt;Insert Then Sort: 00:00:00.0018287&lt;br&gt;Random 100000&lt;br&gt;BinaryInsert:&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; 00:00:02.4289054&lt;br&gt;Insert Then Sort: 00:00:00.0237019&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;As you can see, based on my sample program, BinaryInsert is much slower than Insert and Sort.&amp;nbsp; I ran the profiler against this and verified the suspicion that List(Of T).Insert() took the vast majority of the time.&amp;nbsp; &lt;p&gt;Perhaps there is a reason BinaryInsert is missing. &lt;pre class="code"&gt;&lt;span style="color: rgb(0,0,255)"&gt;Module&lt;/span&gt; Module1

    &lt;span style="color: rgb(0,0,255)"&gt;Function&lt;/span&gt; BinaryInsert(&lt;span style="color: rgb(0,0,255)"&gt;Of&lt;/span&gt; T)(&lt;span style="color: rgb(0,0,255)"&gt;ByVal&lt;/span&gt; enumerable &lt;span style="color: rgb(0,0,255)"&gt;As&lt;/span&gt; IEnumerable(&lt;span style="color: rgb(0,0,255)"&gt;Of&lt;/span&gt; T), &lt;span style="color: rgb(0,0,255)"&gt;ByVal&lt;/span&gt; comp &lt;span style="color: rgb(0,0,255)"&gt;As&lt;/span&gt; IComparer(&lt;span style="color: rgb(0,0,255)"&gt;Of&lt;/span&gt; T)) &lt;span style="color: rgb(0,0,255)"&gt;As&lt;/span&gt; TimeSpan
        &lt;span style="color: rgb(0,0,255)"&gt;Dim&lt;/span&gt; list &lt;span style="color: rgb(0,0,255)"&gt;As&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;New&lt;/span&gt; List(&lt;span style="color: rgb(0,0,255)"&gt;Of&lt;/span&gt; T)
        &lt;span style="color: rgb(0,0,255)"&gt;Dim&lt;/span&gt; watch &lt;span style="color: rgb(0,0,255)"&gt;As&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;New&lt;/span&gt; Stopwatch()

        watch.Start()
        &lt;span style="color: rgb(0,0,255)"&gt;For&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Each&lt;/span&gt; value &lt;span style="color: rgb(0,0,255)"&gt;In&lt;/span&gt; enumerable
            list.BinaryInsert(value, comp)
        &lt;span style="color: rgb(0,0,255)"&gt;Next
&lt;/span&gt;        watch.Stop()
        &lt;span style="color: rgb(0,0,255)"&gt;Return&lt;/span&gt; watch.Elapsed
    &lt;span style="color: rgb(0,0,255)"&gt;End&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Function

&lt;/span&gt;    &lt;span style="color: rgb(0,0,255)"&gt;Function&lt;/span&gt; InsertAllThenSort(&lt;span style="color: rgb(0,0,255)"&gt;Of&lt;/span&gt; T)(&lt;span style="color: rgb(0,0,255)"&gt;ByVal&lt;/span&gt; enumerable &lt;span style="color: rgb(0,0,255)"&gt;As&lt;/span&gt; IEnumerable(&lt;span style="color: rgb(0,0,255)"&gt;Of&lt;/span&gt; T), &lt;span style="color: rgb(0,0,255)"&gt;ByVal&lt;/span&gt; comp &lt;span style="color: rgb(0,0,255)"&gt;As&lt;/span&gt; IComparer(&lt;span style="color: rgb(0,0,255)"&gt;Of&lt;/span&gt; T)) &lt;span style="color: rgb(0,0,255)"&gt;As&lt;/span&gt; TimeSpan
        &lt;span style="color: rgb(0,0,255)"&gt;Dim&lt;/span&gt; list &lt;span style="color: rgb(0,0,255)"&gt;As&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;New&lt;/span&gt; List(&lt;span style="color: rgb(0,0,255)"&gt;Of&lt;/span&gt; T)
        &lt;span style="color: rgb(0,0,255)"&gt;Dim&lt;/span&gt; watch &lt;span style="color: rgb(0,0,255)"&gt;As&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;New&lt;/span&gt; Stopwatch()

        watch.Start()
        &lt;span style="color: rgb(0,0,255)"&gt;For&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Each&lt;/span&gt; value &lt;span style="color: rgb(0,0,255)"&gt;In&lt;/span&gt; enumerable
            list.Add(value)
        &lt;span style="color: rgb(0,0,255)"&gt;Next
&lt;/span&gt;        list.Sort(comp)
        watch.Stop()
        &lt;span style="color: rgb(0,0,255)"&gt;Return&lt;/span&gt; watch.Elapsed
    &lt;span style="color: rgb(0,0,255)"&gt;End&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Function

&lt;/span&gt;    &lt;span style="color: rgb(0,0,255)"&gt;Sub&lt;/span&gt; TestBoth(&lt;span style="color: rgb(0,0,255)"&gt;Of&lt;/span&gt; T)(&lt;span style="color: rgb(0,0,255)"&gt;ByVal&lt;/span&gt; title &lt;span style="color: rgb(0,0,255)"&gt;As&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;String&lt;/span&gt;, &lt;span style="color: rgb(0,0,255)"&gt;ByVal&lt;/span&gt; enumerable &lt;span style="color: rgb(0,0,255)"&gt;As&lt;/span&gt; IEnumerable(&lt;span style="color: rgb(0,0,255)"&gt;Of&lt;/span&gt; T))
        TestBoth(title, enumerable, Comparer(&lt;span style="color: rgb(0,0,255)"&gt;Of&lt;/span&gt; T).Default)
    &lt;span style="color: rgb(0,0,255)"&gt;End&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Sub

&lt;/span&gt;    &lt;span style="color: rgb(0,0,255)"&gt;Sub&lt;/span&gt; TestBoth(&lt;span style="color: rgb(0,0,255)"&gt;Of&lt;/span&gt; T)(&lt;span style="color: rgb(0,0,255)"&gt;ByVal&lt;/span&gt; title &lt;span style="color: rgb(0,0,255)"&gt;As&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;String&lt;/span&gt;, &lt;span style="color: rgb(0,0,255)"&gt;ByVal&lt;/span&gt; enumerable &lt;span style="color: rgb(0,0,255)"&gt;As&lt;/span&gt; IEnumerable(&lt;span style="color: rgb(0,0,255)"&gt;Of&lt;/span&gt; T), &lt;span style="color: rgb(0,0,255)"&gt;ByVal&lt;/span&gt; comp &lt;span style="color: rgb(0,0,255)"&gt;As&lt;/span&gt; IComparer(&lt;span style="color: rgb(0,0,255)"&gt;Of&lt;/span&gt; T))
        &lt;span style="color: rgb(0,0,255)"&gt;Dim&lt;/span&gt; copy = &lt;span style="color: rgb(0,0,255)"&gt;New&lt;/span&gt; List(&lt;span style="color: rgb(0,0,255)"&gt;Of&lt;/span&gt; T)(enumerable)
        &lt;span style="color: rgb(0,0,255)"&gt;Dim&lt;/span&gt; ellapsedBinary = BinaryInsert(&lt;span style="color: rgb(0,0,255)"&gt;New&lt;/span&gt; List(&lt;span style="color: rgb(0,0,255)"&gt;Of&lt;/span&gt; T)(copy), comp)
        &lt;span style="color: rgb(0,0,255)"&gt;Dim&lt;/span&gt; ellapsedSort = InsertAllThenSort(&lt;span style="color: rgb(0,0,255)"&gt;New&lt;/span&gt; List(&lt;span style="color: rgb(0,0,255)"&gt;Of&lt;/span&gt; T)(copy), comp)

        Console.WriteLine(title)
        Console.WriteLine(&lt;span style="color: rgb(163,21,21)"&gt;"BinaryInsert:     {0}"&lt;/span&gt;, ellapsedBinary)
        Console.WriteLine(&lt;span style="color: rgb(163,21,21)"&gt;"Insert Then Sort: {0}"&lt;/span&gt;, ellapsedSort)
    &lt;span style="color: rgb(0,0,255)"&gt;End&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Sub

&lt;/span&gt;    &lt;span style="color: rgb(0,0,255)"&gt;Function&lt;/span&gt; Range(&lt;span style="color: rgb(0,0,255)"&gt;ByVal&lt;/span&gt; start &lt;span style="color: rgb(0,0,255)"&gt;As&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Integer&lt;/span&gt;, &lt;span style="color: rgb(0,0,255)"&gt;ByVal&lt;/span&gt; count &lt;span style="color: rgb(0,0,255)"&gt;As&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Integer&lt;/span&gt;) &lt;span style="color: rgb(0,0,255)"&gt;As&lt;/span&gt; List(&lt;span style="color: rgb(0,0,255)"&gt;Of&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Integer&lt;/span&gt;)
        &lt;span style="color: rgb(0,0,255)"&gt;Dim&lt;/span&gt; list = &lt;span style="color: rgb(0,0,255)"&gt;New&lt;/span&gt; List(&lt;span style="color: rgb(0,0,255)"&gt;Of&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Integer&lt;/span&gt;)
        &lt;span style="color: rgb(0,0,255)"&gt;For&lt;/span&gt; i = start &lt;span style="color: rgb(0,0,255)"&gt;To&lt;/span&gt; count - 1
            list.Add(i)
        &lt;span style="color: rgb(0,0,255)"&gt;Next
&lt;/span&gt;        &lt;span style="color: rgb(0,0,255)"&gt;Return&lt;/span&gt; list
    &lt;span style="color: rgb(0,0,255)"&gt;End&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Function

&lt;/span&gt;    &lt;span style="color: rgb(0,0,255)"&gt;Function&lt;/span&gt; Random(&lt;span style="color: rgb(0,0,255)"&gt;ByVal&lt;/span&gt; count &lt;span style="color: rgb(0,0,255)"&gt;As&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Integer&lt;/span&gt;) &lt;span style="color: rgb(0,0,255)"&gt;As&lt;/span&gt; List(&lt;span style="color: rgb(0,0,255)"&gt;Of&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Integer&lt;/span&gt;)
        &lt;span style="color: rgb(0,0,255)"&gt;Dim&lt;/span&gt; rand &lt;span style="color: rgb(0,0,255)"&gt;As&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;New&lt;/span&gt; Random()
        &lt;span style="color: rgb(0,0,255)"&gt;Dim&lt;/span&gt; list = &lt;span style="color: rgb(0,0,255)"&gt;New&lt;/span&gt; List(&lt;span style="color: rgb(0,0,255)"&gt;Of&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Integer&lt;/span&gt;)
        &lt;span style="color: rgb(0,0,255)"&gt;For&lt;/span&gt; i = 0 &lt;span style="color: rgb(0,0,255)"&gt;To&lt;/span&gt; count - 1
            list.Add(rand.Next())
        &lt;span style="color: rgb(0,0,255)"&gt;Next
&lt;/span&gt;        &lt;span style="color: rgb(0,0,255)"&gt;Return&lt;/span&gt; list
    &lt;span style="color: rgb(0,0,255)"&gt;End&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Function

&lt;/span&gt;    &lt;span style="color: rgb(0,0,255)"&gt;Sub&lt;/span&gt; Main()
        TestBoth(&lt;span style="color: rgb(163,21,21)"&gt;"Force Jit"&lt;/span&gt;, &lt;span style="color: rgb(0,0,255)"&gt;New&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Integer&lt;/span&gt;() {1})
        TestBoth(&lt;span style="color: rgb(163,21,21)"&gt;"Range (0-99)"&lt;/span&gt;, Range(0, 100))
        TestBoth(&lt;span style="color: rgb(163,21,21)"&gt;"Random 10"&lt;/span&gt;, Random(10))
        TestBoth(&lt;span style="color: rgb(163,21,21)"&gt;"Random 100"&lt;/span&gt;, Random(100))
        TestBoth(&lt;span style="color: rgb(163,21,21)"&gt;"Random 1000"&lt;/span&gt;, Random(1000))
        TestBoth(&lt;span style="color: rgb(163,21,21)"&gt;"Random 10000"&lt;/span&gt;, Random(10000))
        TestBoth(&lt;span style="color: rgb(163,21,21)"&gt;"Random 100000"&lt;/span&gt;, Random(100000))
    &lt;span style="color: rgb(0,0,255)"&gt;End&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Sub

End&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Module&lt;/span&gt;&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=8349083" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/jaredpar/archive/tags/VB/">VB</category></item><item><title>Have a IComparable(Of T) but need an IComparer(Of T)?</title><link>http://blogs.msdn.com/b/jaredpar/archive/2008/04/02/have-a-icomparable-of-t-but-need-an-icomparer-of-t.aspx</link><pubDate>Thu, 03 Apr 2008 04:33:52 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:8344484</guid><dc:creator>JaredPar MSFT</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/jaredpar/rsscomments.aspx?WeblogPostID=8344484</wfw:commentRss><comments>http://blogs.msdn.com/b/jaredpar/archive/2008/04/02/have-a-icomparable-of-t-but-need-an-icomparer-of-t.aspx#comments</comments><description>&lt;p&gt;&lt;a href="http://msdn2.microsoft.com/en-us/library/4d7sx9hd.aspx"&gt;IComparable(Of T)&lt;/a&gt; is an interface saying &amp;quot;I can compare myself to other objects of the same type&amp;quot;.&amp;#160; And &lt;a href="http://msdn2.microsoft.com/en-us/library/8ehhxeaf.aspx"&gt;IComparer(Of T)&lt;/a&gt; is an interface saying &amp;quot;I can compare two objects of this type.&amp;quot;.&amp;#160; Often API's which need to perform comparisons will take an instance of IComparer(Of T) instead of IComparable(Of T).&amp;#160; &lt;/p&gt;  &lt;p&gt;Doing the opposite is limiting in a few ways.&amp;#160; The first is it locks developers into the behavior defined by the type author essentially preventing them from deciding to compare in a different way.&amp;#160; The second is if the type author didn't didn't implement IComparable(Of T), we must define a wrapper class that does.&amp;#160; This is even more awkward because collections now contain instances of the wrapper.&amp;#160; Also there is one wrapper overhead per instance in the collection.&amp;#160; &lt;/p&gt;  &lt;p&gt;Now back to the original problem, we have a type which implements IComparable(Of T) but don't have an IComparer(Of T) wrapper class.&amp;#160; Luckily the .Net Framework provides a solution.&amp;#160; Comparer(Of T).Default.&amp;#160; It provides a quick IComparer(Of T) wrapper that automatically delegates to IComparable(Of T) if the type defines it.&amp;#160; &lt;/p&gt;  &lt;p&gt;Example usage:&amp;#160; &lt;a href="http://blogs.msdn.com/jaredpar/archive/2008/03/31/missing-api-list-of-t-binaryinsert.aspx"&gt;Previously&lt;/a&gt; we defined a BinaryInsert method for List(Of T).&amp;#160; It required an explicit IComparer(Of T) be passed even for simple types like Int32.&amp;#160; We can fix this by using the Comparer(Of T) class.&amp;#160; &lt;/p&gt;  &lt;pre class="code"&gt;    &amp;lt;Extension()&amp;gt; _
    &lt;span style="color: rgb(0,0,255)"&gt;Public&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Sub&lt;/span&gt; BinaryInsert(&lt;span style="color: rgb(0,0,255)"&gt;Of&lt;/span&gt; T)(&lt;span style="color: rgb(0,0,255)"&gt;ByVal&lt;/span&gt; list &lt;span style="color: rgb(0,0,255)"&gt;As&lt;/span&gt; List(&lt;span style="color: rgb(0,0,255)"&gt;Of&lt;/span&gt; T), &lt;span style="color: rgb(0,0,255)"&gt;ByVal&lt;/span&gt; value &lt;span style="color: rgb(0,0,255)"&gt;As&lt;/span&gt; T)
        list.BinaryInsert(value, Comparer(&lt;span style="color: rgb(0,0,255)"&gt;Of&lt;/span&gt; T).Default)
    &lt;span style="color: rgb(0,0,255)"&gt;End&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Sub&lt;/span&gt;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=8344484" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/jaredpar/archive/tags/VB/">VB</category><category domain="http://blogs.msdn.com/b/jaredpar/archive/tags/Patterns/">Patterns</category></item><item><title>Missing API: List(Of T).BinaryInsert</title><link>http://blogs.msdn.com/b/jaredpar/archive/2008/03/31/missing-api-list-of-t-binaryinsert.aspx</link><pubDate>Mon, 31 Mar 2008 17:26:42 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:8344445</guid><dc:creator>JaredPar MSFT</dc:creator><slash:comments>3</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/jaredpar/rsscomments.aspx?WeblogPostID=8344445</wfw:commentRss><comments>http://blogs.msdn.com/b/jaredpar/archive/2008/03/31/missing-api-list-of-t-binaryinsert.aspx#comments</comments><description>&lt;p&gt;One API that seems to be missing from &lt;a href="http://msdn2.microsoft.com/en-us/library/6sh2ey19.aspx"&gt;List(Of T)&lt;/a&gt; is a BinaryInsert method.&amp;#160; Especially since there is already a &lt;a href="http://msdn2.microsoft.com/en-us/library/3f90y839.aspx"&gt;BinarySearch&lt;/a&gt; method. &lt;/p&gt;  &lt;p&gt;Binary insert is a method for inserting a value into an already sorted list.&amp;#160; Since the list is already sorted we can do a binary search to find the appropriate place to insert.&amp;#160; The insert keeps the list sorted so the cost of a binary insert is just the cost of the search which is O(Log(N)).&amp;#160; &lt;/p&gt;  &lt;p&gt;An alternative method for keeping a sorted list sorted is to insert and then resort.&amp;#160; Most sorting algorithms have a cost of O(N*Log(N)).&amp;#160; In other words it's N times more expensive. &lt;/p&gt;  &lt;p&gt;Yet this API doesn't exist.&amp;#160; No matter.&amp;#160; We can quickly fix this problem with a couple of extension methods.&amp;#160; &lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: rgb(0,0,255)"&gt;Public&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Module&lt;/span&gt; Extensions

    &amp;lt;Extension()&amp;gt; _
    &lt;span style="color: rgb(0,0,255)"&gt;Public&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Sub&lt;/span&gt; BinaryInsert(&lt;span style="color: rgb(0,0,255)"&gt;Of&lt;/span&gt; T)(&lt;span style="color: rgb(0,0,255)"&gt;ByVal&lt;/span&gt; list &lt;span style="color: rgb(0,0,255)"&gt;As&lt;/span&gt; List(&lt;span style="color: rgb(0,0,255)"&gt;Of&lt;/span&gt; T), &lt;span style="color: rgb(0,0,255)"&gt;ByVal&lt;/span&gt; value &lt;span style="color: rgb(0,0,255)"&gt;As&lt;/span&gt; T, &lt;span style="color: rgb(0,0,255)"&gt;ByVal&lt;/span&gt; comp &lt;span style="color: rgb(0,0,255)"&gt;As&lt;/span&gt; IComparer(&lt;span style="color: rgb(0,0,255)"&gt;Of&lt;/span&gt; T))
        list.BinaryInsert(value, comp, 0, list.Count)
    &lt;span style="color: rgb(0,0,255)"&gt;End&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Sub

&lt;/span&gt;    &amp;lt;Extension()&amp;gt; _
    &lt;span style="color: rgb(0,0,255)"&gt;Public&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Sub&lt;/span&gt; BinaryInsert(&lt;span style="color: rgb(0,0,255)"&gt;Of&lt;/span&gt; T)(&lt;span style="color: rgb(0,0,255)"&gt;ByVal&lt;/span&gt; list &lt;span style="color: rgb(0,0,255)"&gt;As&lt;/span&gt; List(&lt;span style="color: rgb(0,0,255)"&gt;Of&lt;/span&gt; T), _
                                  &lt;span style="color: rgb(0,0,255)"&gt;ByVal&lt;/span&gt; value &lt;span style="color: rgb(0,0,255)"&gt;As&lt;/span&gt; T, _
                                  &lt;span style="color: rgb(0,0,255)"&gt;ByVal&lt;/span&gt; comparer &lt;span style="color: rgb(0,0,255)"&gt;As&lt;/span&gt; IComparer(&lt;span style="color: rgb(0,0,255)"&gt;Of&lt;/span&gt; T), _
                                  &lt;span style="color: rgb(0,0,255)"&gt;ByVal&lt;/span&gt; iStart &lt;span style="color: rgb(0,0,255)"&gt;As&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Integer&lt;/span&gt;, _
                                  &lt;span style="color: rgb(0,0,255)"&gt;ByVal&lt;/span&gt; iEnd &lt;span style="color: rgb(0,0,255)"&gt;As&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Integer&lt;/span&gt;)
        &lt;span style="color: rgb(0,0,255)"&gt;While&lt;/span&gt; iStart &amp;lt; iEnd
            &lt;span style="color: rgb(0,0,255)"&gt;Dim&lt;/span&gt; len = iEnd - iStart
            &lt;span style="color: rgb(0,0,255)"&gt;Dim&lt;/span&gt; iMiddle = iStart + (len \ 2)
            &lt;span style="color: rgb(0,0,255)"&gt;Dim&lt;/span&gt; comp = comparer.Compare(value, list(iMiddle))
            &lt;span style="color: rgb(0,0,255)"&gt;If&lt;/span&gt; 0 = comp &lt;span style="color: rgb(0,0,255)"&gt;Then
&lt;/span&gt;                iStart = iMiddle
                &lt;span style="color: rgb(0,0,255)"&gt;Exit&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;While
&lt;/span&gt;            &lt;span style="color: rgb(0,0,255)"&gt;ElseIf&lt;/span&gt; comp &amp;lt; 0 &lt;span style="color: rgb(0,0,255)"&gt;Then
&lt;/span&gt;                iEnd = iMiddle
            &lt;span style="color: rgb(0,0,255)"&gt;Else
&lt;/span&gt;                iStart = iMiddle + (len &lt;span style="color: rgb(0,0,255)"&gt;Mod&lt;/span&gt; 2)
            &lt;span style="color: rgb(0,0,255)"&gt;End&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;If
&lt;/span&gt;        &lt;span style="color: rgb(0,0,255)"&gt;End&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;While
&lt;/span&gt;        list.Insert(iStart, value)
    &lt;span style="color: rgb(0,0,255)"&gt;End&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Sub

End&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Module&lt;/span&gt;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=8344445" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/jaredpar/archive/tags/VB/">VB</category><category domain="http://blogs.msdn.com/b/jaredpar/archive/tags/Patterns/">Patterns</category></item><item><title>Dealing with Exceptions in a Future</title><link>http://blogs.msdn.com/b/jaredpar/archive/2008/02/11/dealing-with-exceptions-in-a-future.aspx</link><pubDate>Mon, 11 Feb 2008 19:36:22 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:7614564</guid><dc:creator>JaredPar MSFT</dc:creator><slash:comments>7</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/jaredpar/rsscomments.aspx?WeblogPostID=7614564</wfw:commentRss><comments>http://blogs.msdn.com/b/jaredpar/archive/2008/02/11/dealing-with-exceptions-in-a-future.aspx#comments</comments><description>&lt;p&gt;Besides waiting, the another important issue when dealing with Futures is how to deal with exceptions thrown by the user specified code.&amp;#160; &lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Option 1: Ignore the Exception&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;Don't take any actions in the future code and force users to write exception free code.&amp;#160; IMHO this is not the best way to approach the problem.&amp;#160; The code will be running in the thread pool and unhandled exceptions in the thread pool result in the taking down of an appdomain/process.&amp;#160; In addition Futures are designed to be simple.&amp;#160; Adding a try/catch around every lambda is not practical and/or readable.&amp;#160; &lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Option 2: Catch and Swallow&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;Catch the exception on the background thread and swallow it.&amp;#160; Silently failing is in many cases worse than actually crashing.&amp;#160; Behavior will become flaky and the user/developer won't have any indication there is an error.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Option 3: Re-throw the Exception when Wait is called&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;Catch and save the exception when it occurs on the background thread.&amp;#160; Then when Wait() is called on a Future re-throw the exception.&amp;#160; This makes exception handled deterministic.&lt;/p&gt;  &lt;p&gt;It's also very similar to the exception handling semantics of calling a method.&amp;#160; The only difference is that users must handle the exception at the point of method completion vs invocation.&amp;#160; For synchronous methods this is just the same point.&lt;/p&gt;  &lt;p&gt;The big downside to this approach is the stack trace information is lost from the exception.&amp;#160; Re-throwing will instead add the stack trace at the point of the re-throw.&amp;#160; Not having stack trace information makes it very difficult to actually track down the source of an error.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Option 4: Re-throw a new Exception when Wait is called &lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;This is very similar to Option #3.&amp;#160; The only difference is when the user calls Wait, throw a new exception and make the original exception an inner exception of the new one.&amp;#160; We'll call this exception FutureException.&amp;#160; This has the advantages of option 3 and in addition will preserve the stack trace information from the original exception.&lt;/p&gt;  &lt;p&gt;There is a downside to this approach though.&amp;#160; Users can no longer have different catch blocks to handle the different types of exceptions that can be thrown.&amp;#160; &lt;/p&gt;  &lt;pre class="code"&gt;            &lt;span style="color: rgb(0,0,255)"&gt;try
&lt;/span&gt;            {
                &lt;span style="color: rgb(43,145,175)"&gt;Future&lt;/span&gt;.Create(() =&amp;gt; SomeOperation());
            }
            &lt;span style="color: rgb(0,0,255)"&gt;catch&lt;/span&gt; (&lt;span style="color: rgb(43,145,175)"&gt;IOException&lt;/span&gt; ex)
            {
                &lt;span style="color: rgb(0,128,0)"&gt;// ...
&lt;/span&gt;            }
            &lt;span style="color: rgb(0,0,255)"&gt;catch&lt;/span&gt; (&lt;span style="color: rgb(43,145,175)"&gt;InvalidOperationException&lt;/span&gt; ex)
            {
                &lt;span style="color: rgb(0,128,0)"&gt;// ...
&lt;/span&gt;            }&lt;/pre&gt;

&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;Instead the user can only catch a Future exception and examine the inner result to take corrective action.&amp;#160; &lt;/p&gt;

&lt;pre class="code"&gt;            &lt;span style="color: rgb(0,0,255)"&gt;try
&lt;/span&gt;            {
                &lt;span style="color: rgb(43,145,175)"&gt;Future&lt;/span&gt;.Create(() =&amp;gt; SomeOperation());
            }
            &lt;span style="color: rgb(0,0,255)"&gt;catch&lt;/span&gt; (&lt;span style="color: rgb(43,145,175)"&gt;FutureException&lt;/span&gt; ex)
            {
                &lt;span style="color: rgb(0,0,255)"&gt;var&lt;/span&gt; type = ex.InnerException.GetType();
                &lt;span style="color: rgb(0,0,255)"&gt;if&lt;/span&gt; (type == &lt;span style="color: rgb(0,0,255)"&gt;typeof&lt;/span&gt;(&lt;span style="color: rgb(43,145,175)"&gt;IOException&lt;/span&gt;))
                {
                    &lt;span style="color: rgb(0,128,0)"&gt;// ...
&lt;/span&gt;                }
                &lt;span style="color: rgb(0,0,255)"&gt;else&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;if&lt;/span&gt; (type == &lt;span style="color: rgb(0,0,255)"&gt;typeof&lt;/span&gt;(&lt;span style="color: rgb(43,145,175)"&gt;InvalidOperationException&lt;/span&gt;))
                {
                    &lt;span style="color: rgb(0,128,0)"&gt;// ...
&lt;/span&gt;                }
            }&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;This doesn't actually limit any functionality but users may find the syntax uncomfortable.&amp;#160; VB users can still do exception filtering but this is not at option for C# users.&amp;#160; &lt;/p&gt;

&lt;pre class="code"&gt;        &lt;span style="color: rgb(0,0,255)"&gt;Try
&lt;/span&gt;            Future.Create(&lt;span style="color: rgb(0,0,255)"&gt;Function&lt;/span&gt;() SomeOperation())
        &lt;span style="color: rgb(0,0,255)"&gt;Catch&lt;/span&gt; ex &lt;span style="color: rgb(0,0,255)"&gt;As&lt;/span&gt; Exception &lt;span style="color: rgb(0,0,255)"&gt;When&lt;/span&gt; ex.InnerException.GetType() &lt;span style="color: rgb(0,0,255)"&gt;Is&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;GetType&lt;/span&gt;(IOException)

        &lt;span style="color: rgb(0,0,255)"&gt;End&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Try&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;The FutureException class is straight forward.&amp;#160; A simple implementation of the exception snippet will do the trick. &lt;/p&gt;

&lt;pre class="code"&gt;    [&lt;span style="color: rgb(0,0,255)"&gt;global&lt;/span&gt;::System.&lt;span style="color: rgb(43,145,175)"&gt;Serializable&lt;/span&gt;]
    &lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;class&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;FutureException&lt;/span&gt; : &lt;span style="color: rgb(43,145,175)"&gt;Exception
&lt;/span&gt;    {


        &lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; FutureException() { }
        &lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; FutureException(&lt;span style="color: rgb(0,0,255)"&gt;string&lt;/span&gt; message) : &lt;span style="color: rgb(0,0,255)"&gt;base&lt;/span&gt;(message) { }
        &lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; FutureException(&lt;span style="color: rgb(0,0,255)"&gt;string&lt;/span&gt; message, &lt;span style="color: rgb(43,145,175)"&gt;Exception&lt;/span&gt; inner) : &lt;span style="color: rgb(0,0,255)"&gt;base&lt;/span&gt;(message, inner) { }
        &lt;span style="color: rgb(0,0,255)"&gt;protected&lt;/span&gt; FutureException(
          System.Runtime.Serialization.&lt;span style="color: rgb(43,145,175)"&gt;SerializationInfo&lt;/span&gt; info,
          System.Runtime.Serialization.&lt;span style="color: rgb(43,145,175)"&gt;StreamingContext&lt;/span&gt; context)
            : &lt;span style="color: rgb(0,0,255)"&gt;base&lt;/span&gt;(info, context) { }
    }&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=7614564" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/jaredpar/archive/tags/VB/">VB</category><category domain="http://blogs.msdn.com/b/jaredpar/archive/tags/C_2300_/">C#</category><category domain="http://blogs.msdn.com/b/jaredpar/archive/tags/Futures/">Futures</category></item><item><title>Tuples Part 1</title><link>http://blogs.msdn.com/b/jaredpar/archive/2008/01/03/tuples-part-1.aspx</link><pubDate>Thu, 03 Jan 2008 19:25:51 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:6969362</guid><dc:creator>JaredPar MSFT</dc:creator><slash:comments>6</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/jaredpar/rsscomments.aspx?WeblogPostID=6969362</wfw:commentRss><comments>http://blogs.msdn.com/b/jaredpar/archive/2008/01/03/tuples-part-1.aspx#comments</comments><description>&lt;p&gt;A tuple in computer science can be described as a set of name/value pairs.&amp;nbsp; In some cases it can be described as simply a set of values that are accessible via an index [1].&amp;nbsp; Previously I discussed how to create a &lt;a href="http://blogs.msdn.com/jaredpar/archive/2007/11/29/tuples-in-powershell.aspx"&gt;Tuple inside of PowerShell&lt;/a&gt;.&amp;nbsp; This series will focus on the use of Tuples in DotNet and how to use PowerShell to generate DotNet code.&amp;nbsp; &lt;/p&gt; &lt;p&gt;This series will also distinguish between mutable and immutable tuples.&amp;nbsp; As DotNet is shifting it's focus on parallel programming, immutable types are becoming more important.&amp;nbsp; Therefore this serious will focus on Tuples as immutable types and later examine mutable tuples.&lt;/p&gt; &lt;p&gt;In Visual Studio 2005, both C# and VB acquired tuples as a part of the programming language in the form of Anonymous Types.&amp;nbsp; These fit all of the properties of a tuple.&amp;nbsp; The one difference is in VB, anonymous types are mutable by default.&amp;nbsp; This can be changed though by using the &lt;strong&gt;Key&lt;/strong&gt; keyword.&amp;nbsp; &lt;/p&gt; &lt;p&gt;However anonymous types are lacking one quality which severely lessens their usefulness.&amp;nbsp; &lt;a href="http://blogs.msdn.com/jaredpar/archive/2007/10/01/casting-to-an-anonymous-type.aspx"&gt;Their type cannot be described&lt;/a&gt;.&amp;nbsp; This prevents them from being used as parameters, fields, generic parameters [2] etc ...&amp;nbsp; Unless you use late binding or terribly awkward casts this is limiting.&amp;nbsp; &lt;/p&gt; &lt;p&gt;To get around this, we will be defining a set of generic tuple class supporting 1-N name value pairs.&amp;nbsp; The great downside is because we will be predefining these types the names in the name value pair will be fixed.&amp;nbsp; We will be using A-N for 1-N pairs. &lt;/p&gt; &lt;p&gt;This is very limiting in itself because it's reducing the expressiveness of a type.&amp;nbsp; Anonymous types are much more expressive since they have names.&amp;nbsp; Now types will have properties A,B, etc ...&amp;nbsp; &lt;/p&gt; &lt;p&gt;For me this still works.&amp;nbsp; In my code, I only end up using tuples when I need to pass data around between tightly coupled classes, or just within the same class.&amp;nbsp;&amp;nbsp; Since the creation and use are so close loosing the full expressiveness of the name is not that limiting.&amp;nbsp; &lt;/p&gt; &lt;p&gt;In addition, our tuple implementation will leverage type inference as much as possible such that the following code can be written.&lt;/p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;pre class="code"&gt;            &lt;span style="color: rgb(0,0,255)"&gt;var&lt;/span&gt; tuple = &lt;span style="color: rgb(43,145,175)"&gt;Tuple&lt;/span&gt;.Create(&lt;span style="color: rgb(163,21,21)"&gt;"foo"&lt;/span&gt;);
            &lt;span style="color: rgb(43,145,175)"&gt;Console&lt;/span&gt;.WriteLine(tuple.A);&lt;/pre&gt;
&lt;p&gt;Why write a script to generate these classes?&amp;nbsp; Wouldn't it just be easier to just do this by hand???&amp;nbsp; Yes and no.&amp;nbsp; If you are doing a fixed set of short used classes then yes, do it by hand.&amp;nbsp; These scripts evolved out of my use of tuples.&amp;nbsp; Once I would settle on a structure and I would think of a new feature I needed.&amp;nbsp; Typically I have tuples defined up to 5 fields.&amp;nbsp; Retyping out a new feature got tiresome and error prone.&amp;nbsp; With a scripting solution I could add a new feature and tests in just a few minutes.&amp;nbsp; The series is very representative of the way my solution changed over time.&amp;nbsp; Simple at first but I added features as the situation dictated.&amp;nbsp; Having a scripting solution saved me a lot of time.&lt;/p&gt;
&lt;p&gt;Next up, generating the basic structure.&amp;nbsp; &lt;/p&gt;
&lt;p&gt;[1] In this case, the index just becomes the name and hence a name/value pair. &lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=6969362" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/jaredpar/archive/tags/PowerShell/">PowerShell</category><category domain="http://blogs.msdn.com/b/jaredpar/archive/tags/VB/">VB</category><category domain="http://blogs.msdn.com/b/jaredpar/archive/tags/C_2300_/">C#</category><category domain="http://blogs.msdn.com/b/jaredpar/archive/tags/Threading/">Threading</category><category domain="http://blogs.msdn.com/b/jaredpar/archive/tags/Immutable/">Immutable</category><category domain="http://blogs.msdn.com/b/jaredpar/archive/tags/Tuple/">Tuple</category></item><item><title>Getting my Fortune</title><link>http://blogs.msdn.com/b/jaredpar/archive/2007/12/03/getting-my-fortune.aspx</link><pubDate>Mon, 03 Dec 2007 20:57:46 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:6646687</guid><dc:creator>JaredPar MSFT</dc:creator><slash:comments>1</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/jaredpar/rsscomments.aspx?WeblogPostID=6646687</wfw:commentRss><comments>http://blogs.msdn.com/b/jaredpar/archive/2007/12/03/getting-my-fortune.aspx#comments</comments><description>&lt;p&gt;&lt;a href="http://en.wikipedia.org/wiki/Fortune_(program)"&gt;Fortune&lt;/a&gt; is a Unix command that gets a random message from a set of databases and displays it on the screen.&amp;#160; These messages have a wide variety but tend to be funny, quirky or famous quotes (most are indeed geeky).&amp;#160; &lt;/p&gt;  &lt;p&gt;Nearly all unix systems have a version of Fortune.&amp;#160; Windows doesn't have any version by default.&amp;#160; It provides no real functionality other than humor and amusement but it's something I miss.&amp;#160; Most users add it to their .profile script so they get a new fortune every time they log in.&lt;/p&gt;  &lt;p&gt;There are a couple of heavy weight options to get fortune on my machine&amp;#160; but I prefer something a bit lighter.&amp;#160; I did a quick search and discovered that &lt;a href="http://www.doughughes.net/index.cfm?event=fortune"&gt;Doug Hughes&lt;/a&gt; implemented a fortune web service.&amp;#160; This is just above as light weight as it gets so I implemented a simple PSCmdlet, get-fortune, to do the work (code below).&lt;/p&gt;  &lt;p&gt;Now I can just add a quick get-fortune to my profile script. &lt;/p&gt;  &lt;p&gt;C:\Users\jaredp&amp;gt; get-fortune pets    &lt;br /&gt;Does the name Pavlov ring a bell?&lt;/p&gt;  &lt;pre&gt;&amp;lt;Cmdlet(VerbsCommon.&lt;span style="color: blue"&gt;Get&lt;/span&gt;, &lt;span style="color: maroon"&gt;&amp;quot;Fortune&amp;quot;&lt;/span&gt;)&amp;gt; _
&lt;span style="color: blue"&gt;Public&lt;/span&gt; &lt;span style="color: blue"&gt;Class&lt;/span&gt; GetFortune
    &lt;span style="color: blue"&gt;Inherits&lt;/span&gt; PSCmdlet

    &lt;span style="color: blue"&gt;Public&lt;/span&gt; &lt;span style="color: blue"&gt;Const&lt;/span&gt; TopicHelpMessage = &lt;span style="color: maroon"&gt;&amp;quot;Restricts fortune output to the specified topic&amp;quot;&lt;/span&gt;

    &lt;span style="color: blue"&gt;Private&lt;/span&gt; m_topic &lt;span style="color: blue"&gt;As&lt;/span&gt; &lt;span style="color: blue"&gt;String&lt;/span&gt; = &lt;span style="color: blue"&gt;String&lt;/span&gt;.Empty
    &lt;span style="color: blue"&gt;Private&lt;/span&gt; m_minimumLength &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; m_maximumLength &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; m_timeout &lt;span style="color: blue"&gt;As&lt;/span&gt; &lt;span style="color: blue"&gt;Integer&lt;/span&gt; = &lt;span style="color: maroon"&gt;100000&lt;/span&gt;

    &amp;lt;Parameter( _
               Position:=&lt;span style="color: maroon"&gt;0&lt;/span&gt;, _
               HelpMessage:=TopicHelpMessage, _
               ValueFromPipeline:=&lt;span style="color: maroon"&gt;True&lt;/span&gt;, _
               ValueFromPipelineByPropertyName:=&lt;span style="color: maroon"&gt;True&lt;/span&gt;)&amp;gt; _
    &lt;span style="color: blue"&gt;Public&lt;/span&gt; &lt;span style="color: blue"&gt;Property&lt;/span&gt; Topic() &lt;span style="color: blue"&gt;As&lt;/span&gt; &lt;span style="color: blue"&gt;String&lt;/span&gt;
        &lt;span style="color: blue"&gt;Get&lt;/span&gt;
            &lt;span style="color: blue"&gt;Return&lt;/span&gt; m_topic
        &lt;span style="color: blue"&gt;End&lt;/span&gt; &lt;span style="color: blue"&gt;Get&lt;/span&gt;
        &lt;span style="color: blue"&gt;Set&lt;/span&gt;(&lt;span style="color: blue"&gt;ByVal&lt;/span&gt; value &lt;span style="color: blue"&gt;As&lt;/span&gt; &lt;span style="color: blue"&gt;String&lt;/span&gt;)
            m_topic = value
        &lt;span style="color: blue"&gt;End&lt;/span&gt; &lt;span style="color: blue"&gt;Set&lt;/span&gt;
    &lt;span style="color: blue"&gt;End&lt;/span&gt; &lt;span style="color: blue"&gt;Property&lt;/span&gt;

    &amp;lt;Parameter(Position:=&lt;span style="color: maroon"&gt;1&lt;/span&gt;)&amp;gt; _
    &lt;span style="color: blue"&gt;Public&lt;/span&gt; &lt;span style="color: blue"&gt;Property&lt;/span&gt; MinimumLength() &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;Get&lt;/span&gt;
            &lt;span style="color: blue"&gt;Return&lt;/span&gt; m_minimumLength
        &lt;span style="color: blue"&gt;End&lt;/span&gt; &lt;span style="color: blue"&gt;Get&lt;/span&gt;
        &lt;span style="color: blue"&gt;Set&lt;/span&gt;(&lt;span style="color: blue"&gt;ByVal&lt;/span&gt; value &lt;span style="color: blue"&gt;As&lt;/span&gt; &lt;span style="color: blue"&gt;Integer&lt;/span&gt;)
            m_minimumLength = value
        &lt;span style="color: blue"&gt;End&lt;/span&gt; &lt;span style="color: blue"&gt;Set&lt;/span&gt;
    &lt;span style="color: blue"&gt;End&lt;/span&gt; &lt;span style="color: blue"&gt;Property&lt;/span&gt;

    &amp;lt;Parameter(Position:=&lt;span style="color: maroon"&gt;2&lt;/span&gt;)&amp;gt; _
    &lt;span style="color: blue"&gt;Public&lt;/span&gt; &lt;span style="color: blue"&gt;Property&lt;/span&gt; MaximumLength() &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;Get&lt;/span&gt;
            &lt;span style="color: blue"&gt;Return&lt;/span&gt; m_maximumLength
        &lt;span style="color: blue"&gt;End&lt;/span&gt; &lt;span style="color: blue"&gt;Get&lt;/span&gt;
        &lt;span style="color: blue"&gt;Set&lt;/span&gt;(&lt;span style="color: blue"&gt;ByVal&lt;/span&gt; value &lt;span style="color: blue"&gt;As&lt;/span&gt; &lt;span style="color: blue"&gt;Integer&lt;/span&gt;)
            m_maximumLength = value
        &lt;span style="color: blue"&gt;End&lt;/span&gt; &lt;span style="color: blue"&gt;Set&lt;/span&gt;
    &lt;span style="color: blue"&gt;End&lt;/span&gt; &lt;span style="color: blue"&gt;Property&lt;/span&gt;

    &amp;lt;Parameter(Position:=&lt;span style="color: maroon"&gt;3&lt;/span&gt;)&amp;gt; _
    &lt;span style="color: blue"&gt;Public&lt;/span&gt; &lt;span style="color: blue"&gt;Property&lt;/span&gt; Timeout() &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;Get&lt;/span&gt;
            &lt;span style="color: blue"&gt;Return&lt;/span&gt; m_timeout
        &lt;span style="color: blue"&gt;End&lt;/span&gt; &lt;span style="color: blue"&gt;Get&lt;/span&gt;
        &lt;span style="color: blue"&gt;Set&lt;/span&gt;(&lt;span style="color: blue"&gt;ByVal&lt;/span&gt; value &lt;span style="color: blue"&gt;As&lt;/span&gt; &lt;span style="color: blue"&gt;Integer&lt;/span&gt;)
            m_timeout = value
        &lt;span style="color: blue"&gt;End&lt;/span&gt; &lt;span style="color: blue"&gt;Set&lt;/span&gt;
    &lt;span style="color: blue"&gt;End&lt;/span&gt; &lt;span style="color: blue"&gt;Property&lt;/span&gt;

    &lt;span style="color: blue"&gt;Protected&lt;/span&gt; &lt;span style="color: blue"&gt;Overrides&lt;/span&gt; &lt;span style="color: blue"&gt;Sub&lt;/span&gt; ProcessRecord()
        &lt;span style="color: blue"&gt;Dim&lt;/span&gt; proxy &lt;span style="color: blue"&gt;As&lt;/span&gt; &lt;span style="color: blue"&gt;New&lt;/span&gt; DougHughes.fortune
        &lt;span style="color: blue"&gt;Dim&lt;/span&gt; topic = m_topic
        &lt;span style="color: blue"&gt;If&lt;/span&gt; topic &lt;span style="color: blue"&gt;Is&lt;/span&gt; &lt;span style="color: blue"&gt;Nothing&lt;/span&gt; &lt;span style="color: blue"&gt;Then&lt;/span&gt;
            topic = &lt;span style="color: blue"&gt;String&lt;/span&gt;.Empty
        &lt;span style="color: blue"&gt;End&lt;/span&gt; &lt;span style="color: blue"&gt;If&lt;/span&gt;

        proxy.Timeout = m_timeout
        WriteObject(proxy.getFortune(topic, m_minimumLength, m_maximumLength))
    &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;img src="http://blogs.msdn.com/aggbug.aspx?PostID=6646687" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/jaredpar/archive/tags/PowerShell/">PowerShell</category><category domain="http://blogs.msdn.com/b/jaredpar/archive/tags/VB/">VB</category></item></channel></rss>
