<?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 : Patterns</title><link>http://blogs.msdn.com/jaredpar/archive/tags/Patterns/default.aspx</link><description>Tags: Patterns</description><dc:language>en-US</dc:language><generator>CommunityServer 2.1 SP1 (Build: 61025.2)</generator><item><title>If you implement IEquatable&lt;T&gt; you still must override Object’s Equals and GetHashCode</title><link>http://blogs.msdn.com/jaredpar/archive/2009/01/15/if-you-implement-iequatable-t-you-still-must-override-object-s-equals-and-gethashcode.aspx</link><pubDate>Thu, 15 Jan 2009 16:00:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9306048</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>0</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/9306048.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=9306048</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=9306048</wfw:comment><description>&lt;p&gt;CLR 2.0 introduced &lt;a href="http://msdn.microsoft.com/en-us/library/ms131187.aspx"&gt;IEquatable&amp;lt;T&amp;gt;&lt;/a&gt; which is an interface that allows for type safe equality comparisons.&amp;#160; Previously, the best available method for comparing equality was the virtual &lt;a href="http://msdn.microsoft.com/en-us/library/system.object.equals.aspx"&gt;Object Equals&lt;/a&gt; method.&amp;#160; The method is loosely typed since it takes an object as a parameter.&amp;#160; This is easy enough to deal with on the client with a simple cast to the appropriate type.&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Student &lt;/span&gt;{
    &lt;span style="color: blue"&gt;public override bool &lt;/span&gt;Equals(&lt;span style="color: blue"&gt;object &lt;/span&gt;obj) {
        &lt;span style="color: blue"&gt;var &lt;/span&gt;other = obj &lt;span style="color: blue"&gt;as &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Student&lt;/span&gt;;
        &lt;span style="color: blue"&gt;if &lt;/span&gt;(other == &lt;span style="color: blue"&gt;null&lt;/span&gt;) {
            &lt;span style="color: blue"&gt;return false&lt;/span&gt;;
        }
        &lt;span style="color: green"&gt;// rest of comparison
    &lt;/span&gt;}
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;IEquatable&amp;lt;T&amp;gt; is a significant improvement over this pattern because it provides a strongly typed equals method.&amp;#160; This protects both the caller and callee from passing incompatible object types.&amp;#160; Additionally it avoids the overhead of boxing for value types.&lt;/p&gt;

&lt;p&gt;These benefits are nice but if you implement IEquatable&amp;lt;T&amp;gt; you still must override Equals(object) and GetHashCode.&amp;#160; Not doing so is wrong and &lt;strong&gt;will&lt;/strong&gt; cause you pain down the road.&amp;#160; I’ve explored this &lt;a href="http://blogs.msdn.com/jaredpar/archive/2008/05/09/iequatable-of-t-and-gethashcode.aspx"&gt;topic&lt;/a&gt; briefly in the past but wanted to expand on it a bit with some concrete examples. &lt;/p&gt;

&lt;p&gt;Before we get into the technical details of why, lets look at this from an expectation point of view.&amp;#160; Implementing IEquatable&amp;lt;T&amp;gt; is a statement that “this object knows what it means to be equal.”&amp;#160; This in effect adds a contract to your class declaring that it knows how to be compared for equality.&amp;#160; Your object should live up to these expectations in order to avoid confusing other programmers who aren’t intimately familiar with your class.&amp;#160; Confusing programmers is rarely a good idea.&amp;#160; &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Issue #1: IEqualityComparer&amp;lt;T&amp;gt; requires GetHashCode()&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Strongly typed collections such as Dictionary&amp;lt;TKey,TValue&amp;gt; and HashSet&amp;lt;T&amp;gt; must be able to compare objects for equality in order to function.&amp;#160; Starting in 2.0, the BCL provides an interface by which object equality semantics can be performed: IEqualityComparer&amp;lt;T&amp;gt;.&amp;#160; This class is used in many other places besides collections, but inspecting the collection classes is the easiest way to get a feel for it’s use.&lt;/p&gt;

&lt;p&gt;Lets take a look at the definition of IEqualityComparer&amp;lt;T&amp;gt;&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public interface &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IEqualityComparer&lt;/span&gt;&amp;lt;T&amp;gt; {
    &lt;span style="color: blue"&gt;bool &lt;/span&gt;Equals(T x, T y);
    &lt;span style="color: blue"&gt;int &lt;/span&gt;GetHashCode(T obj);
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;The default definition is an internal class in the BCL named GenericEqualityComparer&amp;lt;T&amp;gt;. The default implementation of IEqualityComparer&amp;lt;T&amp;gt; relies on IEquatable&amp;lt;T&amp;gt; for it’s implementation.&amp;#160; &lt;/p&gt;

&lt;p&gt;But if it uses IEquatable&amp;lt;T&amp;gt; for it’s implementation how can it possible implement GetHashCode()?&amp;#160; Simple, it uses Object.GetHashCode().&amp;#160; This means an object must implement IEquatable&amp;lt;T&amp;gt; and GetHashCode() in order to function correctly in places where IEqualityComparer&amp;lt;T&amp;gt; is used.&lt;/p&gt;

&lt;p&gt;But wait, I don’t actually implement IEqualityComparer&amp;lt;T&amp;gt; anywhere so I’m safe right?&amp;#160; Unfortunately no.&amp;#160; Very few people actually implement IEqualityComparer&amp;lt;T&amp;gt;.&amp;#160; Instead they use EqualityComparere&amp;lt;T&amp;gt;.Default to access a given IEqualityComparer&amp;lt;T&amp;gt; for a given type T.&amp;#160; &lt;/p&gt;

&lt;p&gt;In fact, the standard pattern for methods which take an IEqualityComparer&amp;lt;T&amp;gt; is to have an overload that doesn’t and pass EqualityComparer&amp;lt;T&amp;gt;.Default to the one that does.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public static class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Example &lt;/span&gt;{
    &lt;span style="color: blue"&gt;public static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IEnumerable&lt;/span&gt;&amp;lt;T&amp;gt; Distinct&amp;lt;T&amp;gt;(&lt;span style="color: blue"&gt;this &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IEnumerable&lt;/span&gt;&amp;lt;T&amp;gt; source) {
        &lt;span style="color: blue"&gt;return &lt;/span&gt;Distinct(source, &lt;span style="color: #2b91af"&gt;EqualityComparer&lt;/span&gt;&amp;lt;T&amp;gt;.Default);
    }
    &lt;span style="color: blue"&gt;public static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IEnumerable&lt;/span&gt;&amp;lt;T&amp;gt; Distinct&amp;lt;T&amp;gt;(
        &lt;span style="color: blue"&gt;this &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IEnumerable&lt;/span&gt;&amp;lt;T&amp;gt; source, 
        &lt;span style="color: #2b91af"&gt;IEqualityComparer&lt;/span&gt;&amp;lt;T&amp;gt; comparer) {
        &lt;span style="color: green"&gt;// implementation
    &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 your object implements IEquatable&amp;lt;T&amp;gt; this will eventually cause it to create an instance of GenericEqualityComparer&amp;lt;T&amp;gt; and hence a reliance on GetHashCode.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Issue #2: Non-Strongly typed collections and Frameworks don’t use IEquatable&amp;lt;T&amp;gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;IEquatable&amp;lt;T&amp;gt; only provides equality comparisons in strongly typed scenarios.&amp;#160; It is not convenient to access this interface in less strongly typed scenarios.&amp;#160; Consider for instance the original 1.0 collection classes: ArrayList, Hashtable, etc …&amp;#160; These are all object based collections and have no way in which to cast to IEquatable&amp;lt;T&amp;gt;.&amp;#160; Instead these collections must rely on the Object based methods of Equality.&amp;#160; &lt;/p&gt;

&lt;p&gt;Without implementing Object.Equals and Object.GetHashCode your type will not actually do any sort of comparison.&amp;#160; This will cause lots of incorrect behavior for programmers who expect the class to understand equality.&amp;#160; &lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Person &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;IEquatable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Person&lt;/span&gt;&amp;gt; {
    &lt;span style="color: blue"&gt;public readonly string &lt;/span&gt;Name;
    &lt;span style="color: blue"&gt;public &lt;/span&gt;Person(&lt;span style="color: blue"&gt;string &lt;/span&gt;name) {
        Name = name;
    }
    &lt;span style="color: blue"&gt;public bool &lt;/span&gt;Equals(&lt;span style="color: #2b91af"&gt;Person &lt;/span&gt;other) {
        &lt;span style="color: blue"&gt;if &lt;/span&gt;(other == &lt;span style="color: blue"&gt;null&lt;/span&gt;) {
            &lt;span style="color: blue"&gt;return false&lt;/span&gt;;
        }
        &lt;span style="color: blue"&gt;return &lt;/span&gt;&lt;span style="color: #2b91af"&gt;StringComparer&lt;/span&gt;.Ordinal.Equals(Name, other.Name);
    }
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;static void &lt;/span&gt;EqualityCheck() {
    &lt;span style="color: blue"&gt;var &lt;/span&gt;p = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Person&lt;/span&gt;(&lt;span style="color: #a31515"&gt;&amp;quot;Bob&amp;quot;&lt;/span&gt;);
    &lt;span style="color: blue"&gt;var &lt;/span&gt;list = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ArrayList&lt;/span&gt;();
    list.Add(p);
    &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(list.Contains(p)); &lt;span style="color: green"&gt;// Prints: True
    &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(list.Contains(&lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Person&lt;/span&gt;(&lt;span style="color: #a31515"&gt;&amp;quot;Bob&amp;quot;&lt;/span&gt;)));    &lt;span style="color: green"&gt;// Prints: False
&lt;/span&gt;}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;This goes against expectation.&amp;#160; Both Person instances in this case are equal by definition of Person yet Contains fails.&amp;#160; Implementing Object.Equals and Object.GetHashCode will remove this confusion.&lt;/p&gt;

&lt;p&gt;The list of frameworks which still use loosely typed collections include WinForms, WPF, WebForms, etc …&amp;#160; It’s almost inevitable that you will end up using a loosely typed collection in your project somewhere.&amp;#160; &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Isssue #3: Equality and hash codes are linked in the BCL&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Rightly or wrongly, equality and hash codes are unbreakably linked in the BCL.&amp;#160; If an object can be compared for equality it also must be able to produce a hashcode.&amp;#160;&amp;#160; This implicit contract exists many places throughout the framework.&amp;#160; &lt;/p&gt;

&lt;p&gt;As previously displayed, implementing Object.Equals() after implementing IEquatable&amp;lt;T&amp;gt; is straight forward and boiler plate code.&amp;#160; Object.GetHashCode can be a bit trickier because there are many &lt;a href="http://blogs.msdn.com/jaredpar/archive/2008/04/28/properly-implementing-equality-in-vb.aspx"&gt;implicit contracts&lt;/a&gt; for GetHashCode.&amp;#160; Often mutable objects cannot provide an efficient hashing mechanism.&amp;#160; In that case just &lt;a href="http://blogs.msdn.com/jaredpar/archive/2008/06/03/making-equality-easier.aspx"&gt;return 1&lt;/a&gt;.&amp;#160; This will satisfy all of the implicit contracts around GetHashCode() and takes little time to do.&amp;#160; Yes, it will cause a Dictionary to effectively be a linked list.&amp;#160; But that’s a heck of a lot better than simply not working at all.&amp;#160; &lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9306048" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Patterns/default.aspx">Patterns</category></item><item><title>Comparing Continuations in F# and C#</title><link>http://blogs.msdn.com/jaredpar/archive/2008/11/10/comparing-continuations-in-f-and-c.aspx</link><pubDate>Mon, 10 Nov 2008 16:00:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9056481</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>4</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/9056481.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=9056481</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=9056481</wfw:comment><description>&lt;p&gt;Lately I’ve been playing quite a bit with F#.&amp;#160; I have several hobby projects I’m working on that take up a bit of my time.&amp;#160; But when I’m not playing around with F# I’m exploring ways to apply certain functional patterns to actual coding on the job and/or porting to my functional library: &lt;a href="http://code.msdn.microsoft.com/RantPack"&gt;RantPack&lt;/a&gt;.&lt;/p&gt;  &lt;p&gt;Recently I’ve been playing around with continuations in F#.&amp;#160; I thought this was a great topic to do a F# comparison with other languages.&amp;#160; In this case C#.&amp;#160; &lt;/p&gt;  &lt;p&gt;Let’s examine a classic use of continuations: a right fold on a list.&amp;#160; For a detailed explanation of fold right and the use of a continuation I suggest taking a look at &lt;a href="http://lorgonblog.spaces.live.com/blog/cns!701679AD17B6D310!170.entry"&gt;Brian's discussion&lt;/a&gt;.&amp;#160; If you’re unfamiliar with continuations I highly suggest that you take a look at this post as Brian gives a great breakdown of continuations and their uses.&lt;/p&gt;  &lt;p&gt;Here's a quick refresher on continuations by example.&amp;#160; Fold right is an operation which reduces a sequence of elements into a single element by processing the list from right to left.&amp;#160; It’s similar to the &lt;a href="http://msdn.microsoft.com/en-us/library/system.linq.enumerable.aggregate.aspx"&gt;LINQ Aggregate&lt;/a&gt; method except Aggregate operations left to right.&amp;#160; &lt;/p&gt;  &lt;p&gt;For this post we’ll be writing FoldRight against a sequence.&amp;#160; I chose sequence vs. the traditional list because it’s present in both languages (F# = seq&amp;lt;’a&amp;gt;, C# = IEnumerable&amp;lt;T&amp;gt;).&amp;#160; It is possible to other F# data structures in C# but the comparison is cleaner when using a type that is native to both languages. &lt;/p&gt;  &lt;p&gt;Sequences are a left to right data structure so processing it right to left is not natural.&amp;#160; After all, with a sequence all the developer has is current and whether or not there is a next element.&amp;#160; Processing the list in a right to left fashion can be done by such acts as reversing the list, or doing a head recursive call.&amp;#160; Both have their detractors. &lt;/p&gt;  &lt;p&gt;Continuations are a different way to process the list.&amp;#160; Instead of processing the list directly we process the list a single element at a time building up a continuation along the way.&amp;#160; For each element a lambda expression is generated representing the work needed to be done for that element.&amp;#160; The value calculated within the lambda will then be passed to the lambda calculated for the previous element.&amp;#160; Once we hit the end of the list, we essentially have a chain of lambda expressions which process each element in the list in reverse order.&amp;#160; All that is needed is to call the final lambda with the starting value and we will effectively process the list in reverse order.&lt;/p&gt;  &lt;p&gt;Simple enough?&amp;#160; Lets take a look at the code.&amp;#160; &lt;/p&gt;  &lt;p&gt;&lt;strong&gt;F# Code&lt;/strong&gt;&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;FoldRight combine (sequence:seq&amp;lt;'a&amp;gt;) acc = 
    &lt;span style="color: blue"&gt;use &lt;/span&gt;e = sequence.GetEnumerator()
    &lt;span style="color: blue"&gt;let rec &lt;/span&gt;inner cont = 
        &lt;span style="color: blue"&gt;match &lt;/span&gt;e.MoveNext() &lt;span style="color: blue"&gt;with
            &lt;/span&gt;| &lt;span style="color: blue"&gt;true -&amp;gt; 
                let &lt;/span&gt;cur = e.Current
                inner (&lt;span style="color: blue"&gt;fun &lt;/span&gt;racc &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;cont (combine cur racc))
            | &lt;span style="color: blue"&gt;false -&amp;gt; &lt;/span&gt;cont acc
    inner (&lt;span style="color: blue"&gt;fun &lt;/span&gt;x &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;x )&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;C# Code&lt;/strong&gt;&amp;#160;&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public static &lt;/span&gt;TAcc FoldRight&amp;lt;TSource, TAcc&amp;gt;(
    &lt;span style="color: blue"&gt;this &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IEnumerable&lt;/span&gt;&amp;lt;TSource&amp;gt; enumerable, 
    &lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;TAcc, TSource, TAcc&amp;gt; combine, 
    TAcc start) {

    &lt;span style="color: blue"&gt;using &lt;/span&gt;(&lt;span style="color: blue"&gt;var &lt;/span&gt;e = enumerable.GetEnumerator()) {
        &lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;TAcc, TAcc&amp;gt;, TAcc&amp;gt; inner = &lt;span style="color: blue"&gt;null&lt;/span&gt;;
        inner = (cont) =&amp;gt; {
              &lt;span style="color: blue"&gt;if &lt;/span&gt;(e.MoveNext()) {
                  &lt;span style="color: blue"&gt;var &lt;/span&gt;cur = e.Current;
                  &lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;TAcc, TAcc&amp;gt; innerCont = (x) =&amp;gt; cont(combine(x, cur));
                  &lt;span style="color: blue"&gt;return &lt;/span&gt;inner(innerCont);
              } &lt;span style="color: blue"&gt;else &lt;/span&gt;{
                  &lt;span style="color: blue"&gt;return &lt;/span&gt;cont(start);
              }
          };
        &lt;span style="color: blue"&gt;return &lt;/span&gt;inner(x =&amp;gt; x);
    }
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;My immediate reaction to the two samples is the conciseness of the F# code.&amp;#160; This is a not a criticism of C# though.&amp;#160; F# is designed to be a concise language and it’s delivery on that goal is evident in this sample.&amp;#160; &lt;/p&gt;

&lt;p&gt;What makes the big difference here is the type inference power of F#.&amp;#160; In the C# sample there are 6 explicit types listed in the code sample.&amp;#160; The F# sample only has a single type listed.&amp;#160; The compiler is able to infer and/or generate the rest of the signatures.&amp;#160; F# also requires less explicit generic parameters 1 vs. 2 in C#.&lt;/p&gt;

&lt;p&gt;The next big difference I see is the awkward way in which the inner lambda expression must be declared in C#.&amp;#160; The lambda expression is called recursively in order to setup the continuation.&amp;#160; In order to do that in C# the lambda must be declared and defined in separate expressions.&amp;#160; Otherwise, a self reference of “inner” inside the body of “inner” will generate a used before defined warning from the compiler.&amp;#160; &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The IL&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Examining the full IL of both functions would take several blog posts.&amp;#160; Not to mention that trying to read disassembled F# much less IL, is like trying to read disassembled C++.&amp;#160; An interesting exercise but a bit time consuming.&amp;#160; &lt;/p&gt;

&lt;p&gt;I did want to focus a bit on one portion of the generated IL.&amp;#160; There is a very significant difference in the way the recursive call to the “inner” lambda is made.&amp;#160; &lt;/p&gt;

&lt;p&gt;F#&lt;/p&gt;

&lt;pre class="code"&gt;    L_0032: ldarg.1 
    L_0033: ldarg.0 
    L_0034: ldfld !0 Test/clo@6T&lt;!U, !A, !V&gt;::acc
    L_0039: tail 
    L_003b: callvirt instance !1 [FSharp.Core]Microsoft.FSharp.Core.FastFunc`2&lt;!U, !V&gt;::Invoke(!0)&lt;/pre&gt;

&lt;p&gt;C#&lt;/p&gt;

&lt;pre class="code"&gt;    
    L_0077: ldarg.0 
    L_0078: ldfld class [System.Core]System.Func`2&lt;class  !1 [System.Core]System.Func`2&gt;&lt;!1,&gt;, !1&amp;gt; ConsoleApplication1.Extensions/&amp;lt;&amp;gt;c__DisplayClass8&lt;!TSource, !TAcc&gt;::inner
    L_007d: ldloc.0 
    L_007e: callvirt instance !1 [System.Core]System.Func`2&lt;class  !TAcc [System.Core]System.Func`2&gt;&lt;!TAcc,&gt;, !TAcc&amp;gt;::Invoke(!0)
    L_0083: stloc.3 &lt;/pre&gt;

&lt;p&gt;In both cases the first 3 lines are building up the 2 parameters necessary for the recursive lambda call.&amp;#160; The closures are structured somewhat differently but the same basic operation is being done.&amp;#160; &lt;/p&gt;

&lt;p&gt;The key difference between the languages is F#’s use of the &lt;a href="http://msdn.microsoft.com/en-us/library/system.reflection.emit.opcodes.tailcall(VS.95).aspx"&gt;tail opcode&lt;/a&gt;.&amp;#160; This opcode tells the CLR the to call the next method in a tail recursive fashion.&amp;#160; This causes the CLR to remove the current method frame from the stack before the next method is called.&amp;#160; Because the method is removed from the stack, the recursive call takes up no additional stack space.&amp;#160; This is true no matter how many times the function is called.&lt;/p&gt;

&lt;p&gt;The C# IL does not have this opcode.&amp;#160; So the recursive call will happen with the current method on the frame.&amp;#160; With a big enough sequence this will cause the process to run out of stack space and generate a StackOverflowException.&amp;#160; This creates a limitation on the number of elements the C# sample can process.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Limits&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;I explored the limits of both samples on my home laptop.&amp;#160; I generated a simple example to sum the sequence with the fold right.&amp;#160; Note: For a sum of ints, a fold left is just as good, but it serves fine for this sample.&lt;/p&gt;

&lt;p&gt;F#&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;sum = FoldRight (&lt;span style="color: blue"&gt;fun &lt;/span&gt;x y &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;x + y) [1..1000000] 0
printfn &lt;span style="color: maroon"&gt;&amp;quot;%d&amp;quot; &lt;/span&gt;sum&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;C#&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;var &lt;/span&gt;source = &lt;span style="color: #2b91af"&gt;Enumerable&lt;/span&gt;.Range(1, 9397);
&lt;span style="color: blue"&gt;var &lt;/span&gt;result = source.FoldRight((x, y) =&amp;gt; x + y, 0);
&lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: #a31515"&gt;&amp;quot;{0}&amp;quot;&lt;/span&gt;, result);&lt;/pre&gt;

&lt;p&gt;The C# sample can process a maximum size of 9397 elements.&amp;#160; After that I encounter a stackoverflow exception. The F# sample however can easily process 1,000,000 elements. &lt;/p&gt;

&lt;p&gt;Closing note.&amp;#160; This not meant to be a post criticizing C#.&amp;#160; It’s meant to be a general comparison of the same technique in two managed languages.&amp;#160; This is a scenario that is far less likely to occur in a C# program.&amp;#160; In an F# program it’s quite simply an expectation and hence the F# compiler is optimized for this scenario.&amp;#160; &lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9056481" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Patterns/default.aspx">Patterns</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/F_2300_/default.aspx">F#</category></item><item><title>Custom Exceptions: When should you create them?</title><link>http://blogs.msdn.com/jaredpar/archive/2008/10/20/custom-exceptions-when-should-you-create-them.aspx</link><pubDate>Mon, 20 Oct 2008 15:00:27 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:8997282</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>5</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/8997282.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=8997282</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=8997282</wfw:comment><description>&lt;p&gt;I think the best answer is: rarely.&amp;#160;&amp;#160; It's really hard to go straight to a justification here though.&amp;#160; I find that answering a different question will eventually shed led on when to create a new exception. &lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&amp;quot;What are the benefits of creating a new/custom exception?&amp;quot;&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;The answers I come up with or have heard before are ...&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;Provides a type safe mechanism for a developer to detect an error condition.&amp;#160; &lt;p&gt;Without a custom exception a developer would be forced to compare an existing value on an existing exception class in order to determine if a particular error occurred.&amp;#160; To ensure this was unique across applications and environments a unique identifier would need to be inserted as well (likely a GUID).&amp;#160; The resulting code would be quite ugly and maintainability would be a question mark.&amp;#160; &lt;/p&gt;   &lt;/li&gt;    &lt;li&gt;Add situation specific data to an exception      &lt;p&gt;Ideally this data would help another developer track down the source of the error. &lt;/p&gt;      &lt;p&gt;But an entirely new exception is not needed to achieve this goal. The base Exception class contains a property named &lt;a href="http://msdn.microsoft.com/en-us/library/system.exception.data.aspx"&gt;Data&lt;/a&gt; which is an open dictionary. Any code which raises an exception is free to add custom data into the exception. This data can then be accessed by the handling code. Unique values still need to be dealt with. But in my experience, accessing a GUID based custom property is a bit more accepted than catching an exception based on some GUID property. &lt;/p&gt;      &lt;p&gt;This is especially true now with extension methods. The lack of type safety in the dictionary and potentially constant string sharing for property names could be hidden inside an extension method&lt;/p&gt;   &lt;/li&gt;    &lt;li&gt;No existing exception adequately described my problem      &lt;p&gt;I'd argue against this because of &lt;a href="http://msdn.microsoft.com/en-us/library/system.invalidoperationexception.aspx"&gt;InvalidOperationException&lt;/a&gt;. Invalid operation should cover most exceptional cases&lt;/p&gt;   &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;So of these reasons only #1 is a stand alone benefit of a new exception.&amp;#160; Now lets re-state this advantage in the context of the original question. &lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;Creating a new exception allows a developer to catch them &lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Simple right?&amp;#160; But what benefit does this give to a developer?&amp;#160; From my experience there are only two reasons to catch an exception.&amp;#160; &lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;It's a particular for which the underlying exceptional problem can be corrected.&amp;#160; Perhaps the user is prompted to fix the condition by performing some outside action (like re-inserting a disk).&lt;/li&gt;    &lt;li&gt;Logging errors for post-mortem debugging.&amp;#160; Note: You could also use the Data dictionary and extension methods above to introduce a new method ShouldLog().&amp;#160; This would allow you to avoid creating a new exception type.&amp;#160; &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Now I think we can answer the original question of this blog post.&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;You should only create a new exception if you expect developers to take corrective action for the problem or to log for post mortem debugging.&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Otherwise, what benefit does creating this exception give you?&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=8997282" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Patterns/default.aspx">Patterns</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/API+Design/default.aspx">API Design</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Exceptions/default.aspx">Exceptions</category></item><item><title>If it's not broken, maybe you should fix it anyway</title><link>http://blogs.msdn.com/jaredpar/archive/2008/10/13/if-it-s-not-broken-maybe-you-should-fix-it-anyway.aspx</link><pubDate>Mon, 13 Oct 2008 15:00:27 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:8977484</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>2</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/8977484.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=8977484</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=8977484</wfw:comment><description>&lt;p&gt;I know this is goes against conventional wisdom but it's something I believe in.&amp;#160; Every sufficiently large project has that section of code nobody wants to go near.&amp;#160; The mere mention of it causes people to leave the room.&amp;#160; It usually has a couple of properties&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;Old and Stagnant &lt;/li&gt;    &lt;li&gt;Critical or important routine &lt;/li&gt;    &lt;li&gt;Fragile &lt;/li&gt;    &lt;li&gt;Written by a developer who doesn't work there anymore &lt;/li&gt;    &lt;li&gt;Undocumented &lt;/li&gt;    &lt;li&gt;Untested &lt;/li&gt;    &lt;li&gt;Poorly understood &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;But it works and usually has for several releases.&amp;#160; By conventional wisdom it is considered &amp;quot;unbroken&amp;quot; and not worthy of changing.&amp;#160; &lt;/p&gt;  &lt;p&gt;I disagree.&amp;#160; Very often I find towards the end of the cycle more and more bugs start popping up in this code.&amp;#160; It's a pattern I've seen in many groups across releases.&amp;#160; These bugs are extremely expensive to fix because they are a) at the end of the cycle and b) being make in a piece of code that no one understands.&amp;#160; Since it's not broken nobody bothered with the code and hence it stayed poorly understood (and likely just as untested).&amp;#160; The bugs are doubly worse because no one wants to go near that code for fear of breaking the world.&amp;#160; &lt;/p&gt;  &lt;p&gt;Why let this code hang around in it's current state?&amp;#160; It's bad and no one understands why.&amp;#160; It's a constant source of pain late in the cycle and often in the middle.&amp;#160; &lt;/p&gt;  &lt;p&gt;I prefer to take a more proactive approach; fix it.&amp;#160; &lt;/p&gt;  &lt;p&gt;At the end of a product cycle I like to identify these pieces of code and attack them in-between releases.&amp;#160; This is a relatively safe point in the release cycle to change poorly understood code.&amp;#160; There is an entire release cycle ahead to catch the bugs introduced (and there will be some).&amp;#160; &lt;/p&gt;  &lt;p&gt;I don't break this code without thought.&amp;#160; I prefer to take a pragmatic approach to the code in the following steps. &lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Attempt to understand the intent of the code (easier said than done).&amp;#160; I contact the original author if possible &lt;/li&gt;    &lt;li&gt;Poll the more senior developers on their understanding of what the code does &lt;/li&gt;    &lt;li&gt;Design a new architecture if needed &lt;/li&gt;    &lt;li&gt;Design a test plan (this is the absolute most important step.&amp;#160; Why fix this if you don't bother testing it?) &lt;/li&gt;    &lt;li&gt;Make the change &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;I've done this, or overseen someone else, on several pieces of code over the last few years.&amp;#160; Thus far it's been a very big success.&amp;#160; &lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=8977484" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Patterns/default.aspx">Patterns</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Refactoring/default.aspx">Refactoring</category></item><item><title>Unfold</title><link>http://blogs.msdn.com/jaredpar/archive/2008/10/07/unfold.aspx</link><pubDate>Tue, 07 Oct 2008 15:00:34 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:8977472</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>3</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/8977472.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=8977472</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=8977472</wfw:comment><description>&lt;p&gt;F# has a handy method called Unfold.&amp;#160; Think of it as the logical opposite of an Aggregate function.&amp;#160; Aggregates take a sequence of elements and convert them to a single element.&amp;#160; An unfold method will take a single element and turn it into a (potentially infinite) sequence of elements.&amp;#160; &lt;/p&gt;  &lt;p&gt;The API is straight forward.&amp;#160; It takes two parameters&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;A seed/start value &lt;/li&gt;    &lt;li&gt;A function which takes in a seed value and returns either an Empty option to indicate the end of a sequence or a value of Type tuple with two arguments.&amp;#160; The first is the next element in the sequence and the second is the next seed value passed into the function.&lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;This is a very powerful function which allows you to quickly build all sorts of interesting functions.&amp;#160; Lets look at a potential implementation of Enumerable.Range as an unfold expression.&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt; Range(&lt;span style="color: blue"&gt;int &lt;/span&gt;start, &lt;span style="color: blue"&gt;int &lt;/span&gt;count)
{
    &lt;span style="color: blue"&gt;return &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Enumerable&lt;/span&gt;.Unfold(
        start,
        x =&amp;gt; x - start &amp;lt; count
            ? &lt;span style="color: #2b91af"&gt;Option&lt;/span&gt;.Create(&lt;span style="color: #2b91af"&gt;Tuple&lt;/span&gt;.Create(x, x + 1))
            : &lt;span style="color: #2b91af"&gt;Option&lt;/span&gt;.Empty);
}&lt;/pre&gt;

&lt;p&gt;Not as efficient as the framework version of Range but a good mental exercise to get your head around using Unfold.&amp;#160; Implementing this method in C# is fairly straight forward.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IEnumerable&lt;/span&gt;&amp;lt;TResult&amp;gt; Unfold&amp;lt;TSource, TResult&amp;gt;(
    TSource state, 
    &lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;TSource, &lt;span style="color: #2b91af"&gt;Option&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Tuple&lt;/span&gt;&amp;lt;TResult, TSource&amp;gt;&amp;gt;&amp;gt; func)
{
    &lt;span style="color: blue"&gt;if &lt;/span&gt;(func == &lt;span style="color: blue"&gt;null&lt;/span&gt;)
    {
        &lt;span style="color: blue"&gt;throw new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ArgumentNullException&lt;/span&gt;(&lt;span style="color: #a31515"&gt;&amp;quot;func&amp;quot;&lt;/span&gt;);
    }

    &lt;span style="color: blue"&gt;return &lt;/span&gt;UnfoldHelper(state, func);
}

&lt;span style="color: blue"&gt;private static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IEnumerable&lt;/span&gt;&amp;lt;TResult&amp;gt; UnfoldHelper&amp;lt;TSource, TResult&amp;gt;(
    TSource state, 
    &lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;TSource, &lt;span style="color: #2b91af"&gt;Option&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Tuple&lt;/span&gt;&amp;lt;TResult, TSource&amp;gt;&amp;gt;&amp;gt; func)
{
    &lt;span style="color: blue"&gt;do
    &lt;/span&gt;{
        &lt;span style="color: blue"&gt;var &lt;/span&gt;result = func(state);
        &lt;span style="color: blue"&gt;if &lt;/span&gt;(!result.HasValue)
        {
            &lt;span style="color: blue"&gt;break&lt;/span&gt;;
        }

        &lt;span style="color: blue"&gt;yield return &lt;/span&gt;result.Value.First;
        state = result.Value.Second;
    } &lt;span style="color: blue"&gt;while &lt;/span&gt;(&lt;span style="color: blue"&gt;true&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=8977472" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Patterns/default.aspx">Patterns</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/F_2300_/default.aspx">F#</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Functional/default.aspx">Functional</category></item><item><title>Functional C#: Providing an Option</title><link>http://blogs.msdn.com/jaredpar/archive/2008/10/06/functional-c-providing-an-option.aspx</link><pubDate>Mon, 06 Oct 2008 15:00:16 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:8977459</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>5</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/8977459.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=8977459</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=8977459</wfw:comment><description>&lt;p&gt;Sorry for the terrible pun in the title.&amp;#160; I wanted to blog about developing an F# style Option class for C# and I couldn't resist.&lt;/p&gt;  &lt;p&gt;The basics of an Option class are very straight forward.&amp;#160; It's a class that either has a value or doesn't.&amp;#160; It's almost like nullable but for every type and allows for nulls to be a valid value.&amp;#160; Here's a straight forward Option class I coded up. &lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public sealed class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt; {
    &lt;span style="color: blue"&gt;private readonly &lt;/span&gt;T m_value;
    &lt;span style="color: blue"&gt;private readonly bool &lt;/span&gt;m_hasValue;
    &lt;span style="color: blue"&gt;public static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt; Empty {
        &lt;span style="color: blue"&gt;get &lt;/span&gt;{ &lt;span style="color: blue"&gt;return new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt;(); }
    }
    &lt;span style="color: blue"&gt;public bool &lt;/span&gt;HasValue {
        &lt;span style="color: blue"&gt;get &lt;/span&gt;{ &lt;span style="color: blue"&gt;return &lt;/span&gt;m_hasValue; }
    }
    &lt;span style="color: blue"&gt;public &lt;/span&gt;T Value {
        &lt;span style="color: blue"&gt;get &lt;/span&gt;{
            &lt;span style="color: blue"&gt;if &lt;/span&gt;(!HasValue) {
                &lt;span style="color: blue"&gt;throw new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;InvalidOperationException&lt;/span&gt;(&lt;span style="color: #a31515"&gt;&amp;quot;Option does not have a value&amp;quot;&lt;/span&gt;);
            }
            &lt;span style="color: blue"&gt;return &lt;/span&gt;m_value;
        }
    }
    &lt;span style="color: blue"&gt;public &lt;/span&gt;Option(T value) {
        m_hasValue = &lt;span style="color: blue"&gt;true&lt;/span&gt;;
        m_value = value;
    }
    &lt;span style="color: blue"&gt;private &lt;/span&gt;Option() {
        m_hasValue = &lt;span style="color: blue"&gt;false&lt;/span&gt;;
        m_value = &lt;span style="color: blue"&gt;default&lt;/span&gt;(T);
    }
}

&lt;span style="color: blue"&gt;public sealed class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Option &lt;/span&gt;{
    &lt;span style="color: blue"&gt;public static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt; Create&amp;lt;T&amp;gt;(T value) {
        &lt;span style="color: blue"&gt;return new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt;(value);
    }
}&lt;/pre&gt;

&lt;p&gt;I modified a bit of terminology to be more consistent with other frameworks I use (Some/None -&amp;gt; Value,HasValue).&amp;#160; It's succinct, generic and has type inference friendly create functions.&amp;#160; Or does it?&amp;#160; &lt;/p&gt;

&lt;p&gt;Lets consider a function which has a return type of Option&amp;lt;int&amp;gt;.&amp;#160; Case 1 is Option with a value.&amp;#160; There is a type inference friendly Option.Create method which makes for a simple return expression.&amp;#160; No types needed.&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: #2b91af"&gt;Option&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt; SomeMethod() {
    &lt;span style="color: blue"&gt;return &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Option&lt;/span&gt;.Create(42);
}&lt;/pre&gt;

&lt;p&gt;Now lets consider Case #2, None.&amp;#160; Here there is no handy inference method because what would we use for inference.&amp;#160; There is no variable with a Type to use so we are forced to be explicit about the type.&amp;#160; &lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: #2b91af"&gt;Option&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt; SomeMethod2() {
    &lt;span style="color: blue"&gt;return &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Option&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt;.Empty;
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;In this case we're not so bad off because we're dealing with a simple type.&amp;#160; But what about more complex types?&amp;#160; Consider for example a hypothetical Unfold method.&amp;#160; The termination expression would be Option&amp;lt;Tuple&amp;lt;int,string&amp;gt;&amp;gt;.Empty.&amp;#160; Anonymous types are even worse since they are unnamable and can not ever be the source of an option with this design.&amp;#160; This really pales in the usage category when compared with F#.&lt;/p&gt;

&lt;p&gt;Lets see if we can do better.&amp;#160; &lt;/p&gt;

&lt;p&gt;First we could consider a design where we have a static creation method Empty which takes variables that aren't ever used.&amp;#160; This will give us the benefit of type inference but at the expense of an API which is faulty to the core.&amp;#160; It forces the user to create parameters that aren't ever used.&amp;#160; Definitely not a good design.&lt;/p&gt;

&lt;p&gt;This leaves us with using a solution that doesn't involve variables of the necessary type.&amp;#160; This essentially forces us into a non-generic solution since we need variables for type inference.&amp;#160; This non-generic Option won't be compatible with our generic return type. But wait, what will the compiler do if two expressions have conflicting types?&amp;#160; Eventually it will attempt to perform a conversion.&amp;#160; So if we make our non-generic empty Option convertible to any generic empty Option we can use the compilers type safety to our advantage.&amp;#160; &lt;/p&gt;

&lt;p&gt;Definition a non-generic empty Option is straight forward.&amp;#160; &lt;br /&gt;&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public sealed class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Option &lt;/span&gt;{
    &lt;span style="color: blue"&gt;private static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Option &lt;/span&gt;s_empty = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Option&lt;/span&gt;();
    &lt;span style="color: blue"&gt;private &lt;/span&gt;Option() {
    }
    &lt;span style="color: blue"&gt;public static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Option &lt;/span&gt;Empty {
        &lt;span style="color: blue"&gt;get &lt;/span&gt;{ &lt;span style="color: blue"&gt;return &lt;/span&gt;s_empty; }
    }
    &lt;span style="color: blue"&gt;public static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt; Create&amp;lt;T&amp;gt;(T value) {
        &lt;span style="color: blue"&gt;return new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt;(value);
    }
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Using a private constructor allows us a high degree of confidence that any Option instance hanging around came from our Empty property and hence represents an empty option.&amp;#160; Now all we need to do is define a conversion on Option&amp;lt;T&amp;gt;.&amp;#160; Essentially we want to say that any non-generic Option is convertible to this instance.&amp;#160; Add the following to Option&amp;lt;T&amp;gt;&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public static implicit operator &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt;(&lt;span style="color: #2b91af"&gt;Option &lt;/span&gt;option) {
    &lt;span style="color: blue"&gt;return &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Option&lt;/span&gt;&amp;lt;T&amp;gt;.Empty;
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Now, we can use an empty option in any generic scenario without having to specify ugly type parameters.&amp;#160; &lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: #2b91af"&gt;Option&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt; SomeMethod3() {
    &lt;span style="color: blue"&gt;return &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Option&lt;/span&gt;.Empty;
}&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=8977459" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Patterns/default.aspx">Patterns</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/F_2300_/default.aspx">F#</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Functional/default.aspx">Functional</category></item><item><title>RantPack Update 2.0.0.2</title><link>http://blogs.msdn.com/jaredpar/archive/2008/07/23/rantpack-update-2-0-0-2.aspx</link><pubDate>Wed, 23 Jul 2008 15:00:13 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:8765442</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>1</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/8765442.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=8765442</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=8765442</wfw:comment><description>&lt;p&gt;Version 2.0.0.2 released.&amp;nbsp; &lt;/p&gt; &lt;p&gt;Summary: RantPack is a utility library I maintain and actively use.&amp;nbsp; The main themes of this library are functional programming, patterns, immutable/pressitent collections, future and other threading primitives.&amp;nbsp; I've placed the code and binaries on &lt;a href="http://code.msdn.microsoft.com/RantPack"&gt;http://code.msdn.microsoft.com/RantPack&lt;/a&gt; for educational and sharing purposes.&lt;/p&gt; &lt;p&gt;Release Link: &lt;a title="https://code.msdn.microsoft.com/Release/ProjectReleases.aspx?ProjectName=RantPack&amp;amp;ReleaseId=1306" href="https://code.msdn.microsoft.com/Release/ProjectReleases.aspx?ProjectName=RantPack&amp;amp;ReleaseId=1306"&gt;https://code.msdn.microsoft.com/Release/ProjectReleases.aspx?ProjectName=RantPack&amp;amp;ReleaseId=1306&lt;/a&gt;&lt;/p&gt; &lt;p&gt;Release Notes:&lt;/p&gt; &lt;ul&gt; &lt;li&gt;Renamed Tuple properties to be more consistent&lt;/li&gt; &lt;ul&gt; &lt;li&gt;Item0, Item1 instead of A,B&lt;/li&gt;&lt;/ul&gt; &lt;li&gt;Added a Match operator&lt;/li&gt; &lt;li&gt;Made Enumerable more compatible&lt;/li&gt; &lt;li&gt;Bug fixes&lt;/li&gt;&lt;/ul&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=8765442" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Patterns/default.aspx">Patterns</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/RantPack/default.aspx">RantPack</category></item><item><title>Yet another rule for Equality</title><link>http://blogs.msdn.com/jaredpar/archive/2008/07/11/yet-another-rule-for-equality.aspx</link><pubDate>Fri, 11 Jul 2008 15:00:24 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:8718812</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>6</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/8718812.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=8718812</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=8718812</wfw:comment><description>&lt;p&gt;"If you implement equality in a child class, including operators, you must implement the equality operators in the base class."&lt;/p&gt; &lt;p&gt;Unfortunately this is another case of learn the hard way but makes sense when you think about it.&amp;nbsp; The below code snippet is an example of the problem that I hit.&amp;nbsp; Even though I have equality properly defined in Child, the equality check goes through Parent.&amp;nbsp; As such the C# compiler will perform the default comparison which is reference equality.&amp;nbsp; &lt;/p&gt; &lt;p&gt;The simple fix is to add the operator ==/!= definitions to Parent which call through EqualityComparer&amp;lt;Parent&amp;gt;.Default.&amp;nbsp; This will end up calling obj.Equals and equality will function correctly.&lt;/p&gt; &lt;p&gt;While this is intuitive when you think about it, it's an easy trap to fall into.&amp;nbsp; It would be nice if there was a Compiler/FXCop warning here.&amp;nbsp; &lt;/p&gt;&lt;pre class="code"&gt;    &lt;span style="color: rgb(0,0,255)"&gt;class&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;Parent&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;Child&lt;/span&gt; : &lt;span style="color: rgb(43,145,175)"&gt;Parent&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;readonly&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;int&lt;/span&gt; Field1;
        &lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; Child(&lt;span style="color: rgb(0,0,255)"&gt;int&lt;/span&gt; value) {
            Field1 = value;
        }

        &lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;override&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;int&lt;/span&gt; GetHashCode() {
            &lt;span style="color: rgb(0,0,255)"&gt;return&lt;/span&gt; Field1;
        }
        &lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;override&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;bool&lt;/span&gt; Equals(&lt;span style="color: rgb(0,0,255)"&gt;object&lt;/span&gt; obj) {
            &lt;span style="color: rgb(0,0,255)"&gt;var&lt;/span&gt; other = obj &lt;span style="color: rgb(0,0,255)"&gt;as&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;Child&lt;/span&gt;;
            &lt;span style="color: rgb(0,0,255)"&gt;if&lt;/span&gt; (other == &lt;span style="color: rgb(0,0,255)"&gt;null&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;return&lt;/span&gt; other.Field1 == Field1;
        }
        &lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;static&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;bool&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;operator&lt;/span&gt; ==(&lt;span style="color: rgb(43,145,175)"&gt;Child&lt;/span&gt; left, &lt;span style="color: rgb(43,145,175)"&gt;Child&lt;/span&gt; right) {
            &lt;span style="color: rgb(0,0,255)"&gt;return&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;EqualityComparer&lt;/span&gt;&amp;lt;&lt;span style="color: rgb(43,145,175)"&gt;Child&lt;/span&gt;&amp;gt;.Default.Equals(left, right);
        }

        &lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;static&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;bool&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;operator&lt;/span&gt; !=(&lt;span style="color: rgb(43,145,175)"&gt;Child&lt;/span&gt; left, &lt;span style="color: rgb(43,145,175)"&gt;Child&lt;/span&gt; right) {
            &lt;span style="color: rgb(0,0,255)"&gt;return&lt;/span&gt; !&lt;span style="color: rgb(43,145,175)"&gt;EqualityComparer&lt;/span&gt;&amp;lt;&lt;span style="color: rgb(43,145,175)"&gt;Child&lt;/span&gt;&amp;gt;.Default.Equals(left, right);
        }
    }

    &lt;span style="color: rgb(0,0,255)"&gt;class&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;Program&lt;/span&gt; {
        &lt;span style="color: rgb(0,0,255)"&gt;static&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;void&lt;/span&gt; Main(&lt;span style="color: rgb(0,0,255)"&gt;string&lt;/span&gt;[] args) {
            &lt;span style="color: rgb(43,145,175)"&gt;Child&lt;/span&gt; child1 = &lt;span style="color: rgb(0,0,255)"&gt;new&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;Child&lt;/span&gt;(42);
            &lt;span style="color: rgb(43,145,175)"&gt;Child&lt;/span&gt; child2 = &lt;span style="color: rgb(0,0,255)"&gt;new&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;Child&lt;/span&gt;(42);
            &lt;span style="color: rgb(43,145,175)"&gt;Parent&lt;/span&gt; parent1 = child1;
            &lt;span style="color: rgb(43,145,175)"&gt;Parent&lt;/span&gt; parent2 = child2;
            &lt;span style="color: rgb(0,0,255)"&gt;bool&lt;/span&gt; isChildEqual = child2 == child1;       &lt;span style="color: rgb(0,128,0)"&gt;// True
&lt;/span&gt;            &lt;span style="color: rgb(0,0,255)"&gt;bool&lt;/span&gt; isParentEqual = parent1 == parent2;    &lt;span style="color: rgb(0,128,0)"&gt;// False
&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=8718812" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Patterns/default.aspx">Patterns</category></item><item><title>Enums vs. Adapters</title><link>http://blogs.msdn.com/jaredpar/archive/2008/06/18/enums-vs-adapters.aspx</link><pubDate>Wed, 18 Jun 2008 15:00:21 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:8598919</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>9</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/8598919.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=8598919</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=8598919</wfw:comment><description>&lt;p&gt;I like Enums and use them frequently for options and behavior.&amp;#160; To an extent I use Enum's to control behavior.&amp;#160; For example&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;enum &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Kind &lt;/span&gt;{
    Kind1,
    Kind2,
    Kind3
}

&lt;span style="color: blue"&gt;class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Example &lt;/span&gt;{
    &lt;span style="color: blue"&gt;private &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Kind &lt;/span&gt;m_kind;

    &lt;span style="color: blue"&gt;public int &lt;/span&gt;SomeAction() {
        &lt;span style="color: blue"&gt;switch &lt;/span&gt;(m_kind1) {
            &lt;span style="color: blue"&gt;case &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Kind&lt;/span&gt;.Kind1:
                &lt;span style="color: blue"&gt;return &lt;/span&gt;ActionForKind1();
            &lt;span style="color: blue"&gt;case &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Kind&lt;/span&gt;.Kind2:
                &lt;span style="color: blue"&gt;return &lt;/span&gt;ActionForKind2();
            &lt;span style="color: blue"&gt;case &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Kind&lt;/span&gt;.Kind3:
                &lt;span style="color: blue"&gt;return &lt;/span&gt;ActionForKind3();
            &lt;span style="color: blue"&gt;default&lt;/span&gt;:
                &lt;span style="color: blue"&gt;throw new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;InvalidOperationException&lt;/span&gt;(&lt;span style="color: #a31515"&gt;&amp;quot;Invalid Kind&amp;quot;&lt;/span&gt;);
        }
    }
}&lt;/pre&gt;

&lt;p&gt;This is an acceptable pattern and use for enums.&amp;#160; However if you take a step back, what I've actually done here is use an enum to implement an &lt;a href="http://en.wikipedia.org/wiki/Adapter_pattern"&gt;adapter pattern&lt;/a&gt;.&amp;#160; I've just been a bit lazy about it and not actually coded up the classes.&amp;#160; &lt;/p&gt;

&lt;p&gt;To an extent though this violates the principle of single use as Example now performs N different behaviors based upon the enum.&amp;#160; But lets face it, if ActionForKindN() is just a simple 2 line function then is it really worth it to create and maintain an adapter pattern?&amp;#160; A purest would likely say yes but I'm more pragmatic and don't believe so.&amp;#160; &lt;/p&gt;

&lt;p&gt;Once the functions reach a certain level of complexity though an adapter pattern is much more suitable.&amp;#160; Over time I find that many of my similar patterns evolve to level.&amp;#160; &lt;/p&gt;

&lt;p&gt;Yet I struggle to define the point at which an adapter is suitable.&amp;#160; After several recent experiences I started adapting the following rules.&amp;#160; If any of them is violated then I switch from an enum based behavior to adapter based behavior. &lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;The Action* method contains state&lt;/li&gt;

  &lt;li&gt;There are more than 2 functions which change their behavior based on the enum value&lt;/li&gt;

  &lt;li&gt;All methods in the class change their behavior based on the enum &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Anyone have a better set?&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=8598919" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Patterns/default.aspx">Patterns</category></item><item><title>Making Equality easier</title><link>http://blogs.msdn.com/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>Jared Parsons</dc:creator><slash:comments>2</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/8569777.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=8569777</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=8569777</wfw:comment><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/jaredpar/archive/tags/VB/default.aspx">VB</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Patterns/default.aspx">Patterns</category></item><item><title>RantPack Update</title><link>http://blogs.msdn.com/jaredpar/archive/2008/06/02/rantpack-update.aspx</link><pubDate>Tue, 03 Jun 2008 03:26:08 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:8570651</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>0</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/8570651.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=8570651</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=8570651</wfw:comment><description>&lt;p&gt;I released a new version of RantPack today.&amp;#160; Mostly this is a bug fix release with a couple of minor new features.&lt;/p&gt;  &lt;p&gt;&lt;a title="https://code.msdn.microsoft.com/Release/ProjectReleases.aspx?ProjectName=RantPack&amp;amp;ReleaseId=1119" href="https://code.msdn.microsoft.com/Release/ProjectReleases.aspx?ProjectName=RantPack&amp;amp;ReleaseId=1119"&gt;https://code.msdn.microsoft.com/Release/ProjectReleases.aspx?ProjectName=RantPack&amp;amp;ReleaseId=1119&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;Features&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;Added a way to shim Immutable collections to non-immutable interfaces to increase the level of interoperability.&amp;#160; The collections are still immutable and throw an exception whenever one of the mutable APIs are called.&amp;#160; However if the collection is used in an immutable fashion, such as data binding, CollectionUtility.Create* can be used to quickly create a wrapper&lt;/li&gt; &lt;/ul&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;var &lt;/span&gt;q = &lt;span style="color: #2b91af"&gt;ImmutableStack&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt;.Empty;
&lt;span style="color: #2b91af"&gt;CollectionUtility&lt;/span&gt;.GetRangeCount(1, 10).ForEach(x =&amp;gt; q = q.Push(x));
&lt;span style="color: #2b91af"&gt;ICollection&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt; list = &lt;span style="color: #2b91af"&gt;CollectionUtility&lt;/span&gt;.CreateICollection(q);

&lt;span style="color: blue"&gt;var &lt;/span&gt;m = &lt;span style="color: #2b91af"&gt;ImmutableAvlTree&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;, &lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt;.Empty;
&lt;span style="color: #2b91af"&gt;CollectionUtility&lt;/span&gt;.GetRangeCount(1, 10).ForEach(x =&amp;gt; m = m.Add(x, x.ToString()));
&lt;span style="color: #2b91af"&gt;IDictionary&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;, &lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt; map = &lt;span style="color: #2b91af"&gt;CollectionUtility&lt;/span&gt;.CreateIDictionary(m);&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;ul&gt;
  &lt;li&gt;Added an immutable queue named ImmutableQueue&lt;/li&gt;

  &lt;li&gt;Added more overloads to Immutable*.Create to allow more interoperability with BCL data structures.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Bugs&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;MutableTuple.GetHashCode() violated the contract for Object.GetHashCode() by allowing updates to mutate the hash code&lt;/li&gt;
&lt;/ul&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=8570651" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Patterns/default.aspx">Patterns</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/RantPack/default.aspx">RantPack</category></item><item><title>do {} while(0) what?</title><link>http://blogs.msdn.com/jaredpar/archive/2008/05/21/do-while-0-what.aspx</link><pubDate>Wed, 21 May 2008 15:00:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:8525927</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>3</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/8525927.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=8525927</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=8525927</wfw:comment><description>&lt;P&gt;A recent check in of mine raised a few eye brows during reviews.&amp;nbsp; I checked in a few macros which ended with/contained a "do{}while(0)" and people were curious as to why.&amp;nbsp; &lt;/P&gt;
&lt;P&gt;In my experience there are two main uses for it.&amp;nbsp; &lt;/P&gt;
&lt;OL&gt;
&lt;LI&gt;Insert an empty statement with no runtime penalty &lt;/LI&gt;
&lt;LI&gt;Group a set of statements into a single statement followable by a semi-colon&lt;/LI&gt;
&lt;OL&gt;
&lt;LI&gt;do { Func1(); Func2() } while(0) &lt;/LI&gt;&lt;/OL&gt;&lt;/OL&gt;
&lt;P&gt;Macros are mutating little constructs which jump back and forth depending on the compile time options.&amp;nbsp; Many macros compile to different expressions based on the options and in some cases they compile to nothing.&amp;nbsp; This is where #1 really comes in hand.&amp;nbsp; Imagine you have the following code.&amp;nbsp; &lt;/P&gt;&lt;PRE&gt;  if(someCondition)
    MY_MACRO();&lt;/PRE&gt;
&lt;P&gt;Compiling MY_MACRO to nothing will cause at the least a compile time warning since you will have essentially if(someCondition);. Instead you can use the do{}while(0) trick.&lt;/P&gt;&lt;PRE&gt;#if CONST_1
#define MY_MACRO() Func1()
#else
#define MY_MACRO() do{}while(0)&lt;/PRE&gt;
&lt;P&gt;Another us is for stylistic reasons.&amp;nbsp; Some camps don't believe a ; should be used as a empty statement and use do{}while(0) instead.&amp;nbsp; I tend to agree.&amp;nbsp; Mainly because one of my early C professors had the same belief.&amp;nbsp; The habit stuck around.&amp;nbsp;&amp;nbsp; &lt;/P&gt;
&lt;P&gt;Update: Changed incorrect use of word expression -&amp;gt; single statement &lt;/P&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=8525927" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/C_2B002B00_/default.aspx">C++</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Patterns/default.aspx">Patterns</category></item><item><title>Switching on Types</title><link>http://blogs.msdn.com/jaredpar/archive/2008/05/16/switching-on-types.aspx</link><pubDate>Fri, 16 May 2008 15:00:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:8506222</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>9</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/8506222.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=8506222</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=8506222</wfw:comment><description>&lt;P&gt;One action I find frustrating in C# is where a particular action needs to be taken based off of the type of a particular object.&amp;nbsp; Ideally I would like to solve this with a switch statement but switch statements only support constant expressions in C# so no luck there.&amp;nbsp; Previously I've had to resort to ugly looking code like the following.&amp;nbsp; &lt;/P&gt;&lt;PRE class=code&gt;&lt;SPAN style="COLOR: #2b91af"&gt;Type &lt;/SPAN&gt;t = sender.GetType();
&lt;SPAN style="COLOR: blue"&gt;if &lt;/SPAN&gt;(t == &lt;SPAN style="COLOR: blue"&gt;typeof&lt;/SPAN&gt;(&lt;SPAN style="COLOR: #2b91af"&gt;Button&lt;/SPAN&gt;)) {
    &lt;SPAN style="COLOR: blue"&gt;var &lt;/SPAN&gt;realObj = (&lt;SPAN style="COLOR: #2b91af"&gt;Button&lt;/SPAN&gt;)sender;
    &lt;SPAN style="COLOR: green"&gt;// Do Something
&lt;/SPAN&gt;}
&lt;SPAN style="COLOR: blue"&gt;else if &lt;/SPAN&gt;(t == &lt;SPAN style="COLOR: blue"&gt;typeof&lt;/SPAN&gt;(&lt;SPAN style="COLOR: #2b91af"&gt;CheckBox&lt;/SPAN&gt;)) {
    &lt;SPAN style="COLOR: blue"&gt;var &lt;/SPAN&gt;realObj = (&lt;SPAN style="COLOR: #2b91af"&gt;CheckBox&lt;/SPAN&gt;)sender;
    &lt;SPAN style="COLOR: green"&gt;// Do something else
&lt;/SPAN&gt;}
&lt;SPAN style="COLOR: blue"&gt;else &lt;/SPAN&gt;{
    &lt;SPAN style="COLOR: green"&gt;// Default action
&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;Yes I realize this isn't the ugliest code but it seems less elegant to me over a standard switch statement and I find the casting tedious.&amp;nbsp; Especially since it requires you to write every type twice.&amp;nbsp; &lt;/P&gt;
&lt;P&gt;What I want to say is "Given this type, execute this block of code."&amp;nbsp; So I decided to run with that this afternoon.&amp;nbsp; Lambdas will serve nicely for the block of code and using type inference will allow us to avoid writing every type out twice.&amp;nbsp; What I ended up with was a class called TypeSwitch with 3 main methods (see bottom of post for full code).&lt;/P&gt;
&lt;UL&gt;
&lt;LI&gt;Do - Entry point where switching begins &lt;/LI&gt;
&lt;LI&gt;Case - Several overloads which take a generic type argument and an Action&amp;lt;T&amp;gt; to run for the object &lt;/LI&gt;
&lt;LI&gt;Default - Optional default action.&amp;nbsp; &lt;/LI&gt;&lt;/UL&gt;
&lt;P&gt;I wrote a quick winforms app to test out the solution.&amp;nbsp; I dropped some random controls on a from and bound the MouseHover event for all of them to a single method.&amp;nbsp; I can now use the following code to print out different messages based on the type.&amp;nbsp; &lt;/P&gt;&lt;PRE class=code&gt;&lt;SPAN style="COLOR: #2b91af"&gt;TypeSwitch&lt;/SPAN&gt;.Do(
    sender,
    &lt;SPAN style="COLOR: #2b91af"&gt;TypeSwitch&lt;/SPAN&gt;.Case&amp;lt;&lt;SPAN style="COLOR: #2b91af"&gt;Button&lt;/SPAN&gt;&amp;gt;(() =&amp;gt; textBox1.Text = &lt;SPAN style="COLOR: #a31515"&gt;"Hit a Button"&lt;/SPAN&gt;),
    &lt;SPAN style="COLOR: #2b91af"&gt;TypeSwitch&lt;/SPAN&gt;.Case&amp;lt;&lt;SPAN style="COLOR: #2b91af"&gt;CheckBox&lt;/SPAN&gt;&amp;gt;(x =&amp;gt; textBox1.Text = &lt;SPAN style="COLOR: #a31515"&gt;"Checkbox is " &lt;/SPAN&gt;+ x.Checked),
    &lt;SPAN style="COLOR: #2b91af"&gt;TypeSwitch&lt;/SPAN&gt;.Default(() =&amp;gt; textBox1.Text = &lt;SPAN style="COLOR: #a31515"&gt;"Not sure what is hovered over"&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;PRE class=code&gt;&lt;SPAN style="COLOR: blue"&gt;&lt;/SPAN&gt;&lt;/PRE&gt;
&lt;P&gt;Notice that for check box I was able to access CheckBox properties in a strongly typed fashion.&amp;nbsp; The underlying case code will optionally pass the first argument to the lambda expression strongly typed to the value specified as the generic argument.&amp;nbsp; &lt;/P&gt;
&lt;P&gt;There are a couple of faults with this approach including Default being anywhere in the list but it was a fun experiment and works well.&amp;nbsp; &lt;/P&gt;
&lt;P&gt;TypeSwitch code.&lt;/P&gt;&lt;PRE class=code&gt;&lt;SPAN style="COLOR: blue"&gt;static class &lt;/SPAN&gt;&lt;SPAN style="COLOR: #2b91af"&gt;TypeSwitch &lt;/SPAN&gt;{
    &lt;SPAN style="COLOR: blue"&gt;public class &lt;/SPAN&gt;&lt;SPAN style="COLOR: #2b91af"&gt;CaseInfo &lt;/SPAN&gt;{
        &lt;SPAN style="COLOR: blue"&gt;public bool &lt;/SPAN&gt;IsDefault { &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;public &lt;/SPAN&gt;&lt;SPAN style="COLOR: #2b91af"&gt;Type &lt;/SPAN&gt;Target { &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;public &lt;/SPAN&gt;&lt;SPAN style="COLOR: #2b91af"&gt;Action&lt;/SPAN&gt;&amp;lt;&lt;SPAN style="COLOR: blue"&gt;object&lt;/SPAN&gt;&amp;gt; Action { &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;public static void &lt;/SPAN&gt;Do(&lt;SPAN style="COLOR: blue"&gt;object &lt;/SPAN&gt;source, &lt;SPAN style="COLOR: blue"&gt;params &lt;/SPAN&gt;&lt;SPAN style="COLOR: #2b91af"&gt;CaseInfo&lt;/SPAN&gt;[] cases) {
        &lt;SPAN style="COLOR: blue"&gt;var &lt;/SPAN&gt;type = source.GetType();
        &lt;SPAN style="COLOR: blue"&gt;foreach &lt;/SPAN&gt;(&lt;SPAN style="COLOR: blue"&gt;var &lt;/SPAN&gt;entry &lt;SPAN style="COLOR: blue"&gt;in &lt;/SPAN&gt;cases) {
            &lt;SPAN style="COLOR: blue"&gt;if &lt;/SPAN&gt;(entry.IsDefault || type == entry.Target) {
                entry.Action(source);
                &lt;SPAN style="COLOR: blue"&gt;break&lt;/SPAN&gt;;
            }
        }
    }

    &lt;SPAN style="COLOR: blue"&gt;public static &lt;/SPAN&gt;&lt;SPAN style="COLOR: #2b91af"&gt;CaseInfo &lt;/SPAN&gt;Case&amp;lt;T&amp;gt;(&lt;SPAN style="COLOR: #2b91af"&gt;Action &lt;/SPAN&gt;action) {
        &lt;SPAN style="COLOR: blue"&gt;return new &lt;/SPAN&gt;&lt;SPAN style="COLOR: #2b91af"&gt;CaseInfo&lt;/SPAN&gt;() {
            Action = x =&amp;gt; action(),
            Target = &lt;SPAN style="COLOR: blue"&gt;typeof&lt;/SPAN&gt;(T)
        };
    }

    &lt;SPAN style="COLOR: blue"&gt;public static &lt;/SPAN&gt;&lt;SPAN style="COLOR: #2b91af"&gt;CaseInfo &lt;/SPAN&gt;Case&amp;lt;T&amp;gt;(&lt;SPAN style="COLOR: #2b91af"&gt;Action&lt;/SPAN&gt;&amp;lt;T&amp;gt; action) {
        &lt;SPAN style="COLOR: blue"&gt;return new &lt;/SPAN&gt;&lt;SPAN style="COLOR: #2b91af"&gt;CaseInfo&lt;/SPAN&gt;() {
            Action = (x) =&amp;gt; action((T)x),
            Target = &lt;SPAN style="COLOR: blue"&gt;typeof&lt;/SPAN&gt;(T)
        };
    }

    &lt;SPAN style="COLOR: blue"&gt;public static &lt;/SPAN&gt;&lt;SPAN style="COLOR: #2b91af"&gt;CaseInfo &lt;/SPAN&gt;Default(&lt;SPAN style="COLOR: #2b91af"&gt;Action &lt;/SPAN&gt;action) {
        &lt;SPAN style="COLOR: blue"&gt;return new &lt;/SPAN&gt;&lt;SPAN style="COLOR: #2b91af"&gt;CaseInfo&lt;/SPAN&gt;() {
            Action = x =&amp;gt; action(),
            IsDefault = &lt;SPAN style="COLOR: blue"&gt;true
        &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;img src="http://blogs.msdn.com/aggbug.aspx?PostID=8506222" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Patterns/default.aspx">Patterns</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Lambda/default.aspx">Lambda</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Type+Inference/default.aspx">Type Inference</category></item><item><title>IEquatable(Of T) and GetHashCode()</title><link>http://blogs.msdn.com/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>Jared Parsons</dc:creator><slash:comments>0</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/8473844.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=8473844</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=8473844</wfw:comment><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/jaredpar/archive/tags/VB/default.aspx">VB</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Patterns/default.aspx">Patterns</category></item><item><title>Properly Implementing Equality in VB</title><link>http://blogs.msdn.com/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>Jared Parsons</dc:creator><slash:comments>6</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/8428051.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=8428051</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=8428051</wfw:comment><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/jaredpar/archive/tags/VB/default.aspx">VB</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Patterns/default.aspx">Patterns</category></item></channel></rss>