<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:creativeCommons="http://backend.userland.com/creativeCommonsRssModule" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>Pirrmann's train of thought</title>
	
	<link>http://www.pirrmann.net</link>
	<description>Pierre Irrmann on coding, and how fun it is, even in the train</description>
	<lastBuildDate>Thu, 21 Mar 2013 05:23:43 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/pirrmann" /><feedburner:info uri="pirrmann" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><creativeCommons:license>http://creativecommons.org/licenses/by-sa/3.0/</creativeCommons:license><xhtml:meta xmlns:xhtml="http://www.w3.org/1999/xhtml" name="robots" content="noindex" /><meta xmlns="http://pipes.yahoo.com" name="pipes" content="noprocess" /><feedburner:feedFlare href="http://add.my.yahoo.com/rss?url=http%3A%2F%2Ffeeds.feedburner.com%2Fpirrmann" src="http://us.i1.yimg.com/us.yimg.com/i/us/my/addtomyyahoo4.gif">Subscribe with My Yahoo!</feedburner:feedFlare><feedburner:feedFlare href="http://www.newsgator.com/ngs/subscriber/subext.aspx?url=http%3A%2F%2Ffeeds.feedburner.com%2Fpirrmann" src="http://www.newsgator.com/images/ngsub1.gif">Subscribe with NewsGator</feedburner:feedFlare><feedburner:feedFlare href="http://feeds.my.aol.com/add.jsp?url=http%3A%2F%2Ffeeds.feedburner.com%2Fpirrmann" src="http://o.aolcdn.com/favorites.my.aol.com/webmaster/ffclient/webroot/locale/en-US/images/myAOLButtonSmall.gif">Subscribe with My AOL</feedburner:feedFlare><feedburner:feedFlare href="http://www.bloglines.com/sub/http://feeds.feedburner.com/pirrmann" src="http://www.bloglines.com/images/sub_modern11.gif">Subscribe with Bloglines</feedburner:feedFlare><feedburner:feedFlare href="http://www.netvibes.com/subscribe.php?url=http%3A%2F%2Ffeeds.feedburner.com%2Fpirrmann" src="http://www.netvibes.com/img/add2netvibes.gif">Subscribe with Netvibes</feedburner:feedFlare><feedburner:feedFlare href="http://fusion.google.com/add?feedurl=http%3A%2F%2Ffeeds.feedburner.com%2Fpirrmann" src="http://buttons.googlesyndication.com/fusion/add.gif">Subscribe with Google</feedburner:feedFlare><feedburner:feedFlare href="http://www.pageflakes.com/subscribe.aspx?url=http%3A%2F%2Ffeeds.feedburner.com%2Fpirrmann" src="http://www.pageflakes.com/ImageFile.ashx?instanceId=Static_4&amp;fileName=ATP_blu_91x17.gif">Subscribe with Pageflakes</feedburner:feedFlare><feedburner:feedFlare href="http://www.plusmo.com/add?url=http%3A%2F%2Ffeeds.feedburner.com%2Fpirrmann" src="http://plusmo.com/res/graphics/fbplusmo.gif">Subscribe with Plusmo</feedburner:feedFlare><feedburner:feedFlare href="http://www.thefreedictionary.com/_/hp/AddRSS.aspx?http%3A%2F%2Ffeeds.feedburner.com%2Fpirrmann" src="http://img.tfd.com/hp/addToTheFreeDictionary.gif">Subscribe with The Free Dictionary</feedburner:feedFlare><feedburner:feedFlare href="http://www.bitty.com/manual/?contenttype=rssfeed&amp;contentvalue=http%3A%2F%2Ffeeds.feedburner.com%2Fpirrmann" src="http://www.bitty.com/img/bittychicklet_91x17.gif">Subscribe with Bitty Browser</feedburner:feedFlare><feedburner:feedFlare href="http://www.live.com/?add=http%3A%2F%2Ffeeds.feedburner.com%2Fpirrmann" src="http://tkfiles.storage.msn.com/x1piYkpqHC_35nIp1gLE68-wvzLZO8iXl_JMledmJQXP-XTBOLfmQv4zhj4MhcWEJh_GtoBIiAl1Mjh-ndp9k47If7hTaFno0mxW9_i3p_5qQw">Subscribe with Live.com</feedburner:feedFlare><feedburner:feedFlare href="http://mix.excite.eu/add?feedurl=http%3A%2F%2Ffeeds.feedburner.com%2Fpirrmann" src="http://image.excite.co.uk/mix/addtomix.gif">Subscribe with Excite MIX</feedburner:feedFlare><feedburner:feedFlare href="http://www.webwag.com/wwgthis.php?url=http%3A%2F%2Ffeeds.feedburner.com%2Fpirrmann" src="http://www.webwag.com/images/wwgthis.gif">Subscribe with Webwag</feedburner:feedFlare><feedburner:feedFlare href="http://www.podcastready.com/oneclick_bookmark.php?url=http%3A%2F%2Ffeeds.feedburner.com%2Fpirrmann" src="http://www.podcastready.com/images/podcastready_button.gif">Subscribe with Podcast Ready</feedburner:feedFlare><feedburner:feedFlare href="http://www.wikio.com/subscribe?url=http%3A%2F%2Ffeeds.feedburner.com%2Fpirrmann" src="http://www.wikio.com/shared/img/add2wikio.gif">Subscribe with Wikio</feedburner:feedFlare><feedburner:feedFlare href="http://www.dailyrotation.com/index.php?feed=http%3A%2F%2Ffeeds.feedburner.com%2Fpirrmann" src="http://www.dailyrotation.com/rss-dr2.gif">Subscribe with Daily Rotation</feedburner:feedFlare><feedburner:browserFriendly>Thanks for suscribing to my blog !</feedburner:browserFriendly><item>
		<title>Pattern matching in C# – part 3 – tuples</title>
		<link>http://feedproxy.google.com/~r/pirrmann/~3/wUZzg5iIvVA/</link>
		<comments>http://www.pirrmann.net/pattern-matching-in-c-part-3-tuples/#comments</comments>
		<pubDate>Wed, 20 Mar 2013 20:58:19 +0000</pubDate>
		<dc:creator>Pierre IRRMANN</dc:creator>
				<category><![CDATA[Functional Inspiration]]></category>
		<category><![CDATA[Syntax Puzzles]]></category>
		<category><![CDATA[AST]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[Puzzle]]></category>

		<guid isPermaLink="false">http://www.pirrmann.net/?p=201</guid>
		<description><![CDATA[Hello again, you potential RSS subscriber (probably still reading this in Google Reader, trying to determine which reader you’ll choose next) ! Last time I left you with a working pattern-matching mechanism in C#, but very limited… as it could &#8230; <a href="http://www.pirrmann.net/pattern-matching-in-c-part-3-tuples/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>Hello again, you potential RSS subscriber (probably still reading this in Google Reader, trying to determine which reader you’ll choose next) ! Last time I left you with a working pattern-matching mechanism in C#, but very limited… as it could only match a single value at a time.</p>
<p>What makes the pattern-matching mechanism so powerful in functional languages is its ability to match many sorts of data structures, amongst which are tuples.</p>
<p>Defining a match expression on a tuple or 2 values in F# can be done this way :</p>
<pre class="brush: fsharp; gutter: false; toolbar: false;">let result =
    match input with
    | 1, 1 -&gt; 1
    | 2, _ -&gt; 2
    | _, 3 -&gt; 3
    | a, b when a &gt; 4 -&gt; 4
    | _ -&gt; 5</pre>
<p>This sample shows some interesting cases. A tuple of 2 values can be matched with several expressions, each value of the tuple being compared with individual patterns.</p>
<p>In part 1 of this series, we stated these individual patterns:</p>
<ul>
<li>a constant pattern,
<li>a conditional pattern,
<li>a default pattern, known as the wildcard pattern (the underscore in F#).</li>
</ul>
<p>Now, we have to handle every possible combination of these patterns!</p>
<p>The following sample translated in C# in my experimental syntax is the following:</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">var tupleSample =
    PatternMatcher.CreateSwitch&lt;int, int, int&gt;()
    .Case(1         , 1, (a, b) =&gt; 1)
    .Case(2         , _, (a, b) =&gt; 2)
    .Case(_         , 3, (a, b) =&gt; 3)
    .Case(a =&gt; a &gt; 4, _, (a, b) =&gt; 4)
    .Case(_         , _, (a, b) =&gt; 5);</pre>
<p>Welcome to the parenthesis hell. Soon it will like like Lisp if we go on… But how do we enable that syntax ?</p>
<p>In order to handle gracefully the wildcard (“_”) pattern, I have used a non-generic <em>MatchCase</em> class with a static field called Any:</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">public class MatchCase
{
    public static readonly MatchCase Any;

    static MatchCase()
    {
        Any = new MatchCase();
    }

    private MatchCase()
    {
    }
}</pre>
<p>This trick allows me to define methods with a <em>MatchCase</em>-typed parameter to handle the wildcard pattern case. Moreover, if I add the following line before my patterns definitions :</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">var _ = MatchCase.Any;</pre>
<p>I’m then able to use a simple “_” to represent the “any” case.</p>
<p>The method used previously to build the pattern matching Func and its invocation in the Eval method doesn’t change: only the “recording” process is impacted. The pain point here is that we need to define each necessary overload of the <em>Case</em> extension method, in order to handle all the patterns. These extensions methods are all based on the following model:</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">public static PatternMatcher&lt;Tuple&lt;T1, T2&gt;, TResult&gt;
    Case&lt;T1, T2, TResult&gt;(
    this PatternMatcher&lt;Tuple&lt;T1, T2&gt;, TResult&gt; pattern,
    {arg1},
    {arg2},
    Expression&lt;Func&lt;T1, T2, TResult&gt;&gt; selector)</pre>
<p>where the {arg1} and {arg2} placeholders are replaced with :</p>
<ul>
<li>T1 testValue1, T2 testValue2
<li>T1 testValue1, Expression&lt;Func&lt;T2, bool&gt;&gt; testExpression2
<li>T1 testValue1, MatchCase any2
<li>Expression&lt;Func&lt;T1, bool&gt;&gt; testExpression1, T2 testValue2
<li>Expression&lt;Func&lt;T1, bool&gt;&gt; testExpression1, Expression&lt;Func&lt;T2, bool&gt;&gt; testExpression2
<li>Expression&lt;Func&lt;T1, bool&gt;&gt; testExpression1, MatchCase any2
<li>MatchCase any1, T2 testValue2
<li>MatchCase any1, Expression&lt;Func&lt;T2, bool&gt;&gt; testExpression2
<li>MatchCase any1, MatchCase any2 </li>
</ul>
<p>The implementation of each method follows the same pattern as in the previous post, and builds an expression that determines whether a given tuple matches the pattern, returning, and evaluates the selector expression when there is a match.</p>
<p>But if we want to handle tuples with more values… do we have to write all the overloads ?!</p>
<img src="http://feeds.feedburner.com/~r/pirrmann/~4/wUZzg5iIvVA" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.pirrmann.net/pattern-matching-in-c-part-3-tuples/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.pirrmann.net/pattern-matching-in-c-part-3-tuples/</feedburner:origLink></item>
		<item>
		<title>Pattern matching in C# – part 2</title>
		<link>http://feedproxy.google.com/~r/pirrmann/~3/W6liSlagDU0/</link>
		<comments>http://www.pirrmann.net/pattern-matching-in-c-part-2/#comments</comments>
		<pubDate>Tue, 19 Mar 2013 05:00:29 +0000</pubDate>
		<dc:creator>Pierre IRRMANN</dc:creator>
				<category><![CDATA[Functional Inspiration]]></category>
		<category><![CDATA[Syntax Puzzles]]></category>
		<category><![CDATA[AST]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[Puzzle]]></category>

		<guid isPermaLink="false">http://www.pirrmann.net/?p=196</guid>
		<description><![CDATA[Last time, I just stopped before generating any real expression tree… Now is the perfect time to continue the process ! In order to handle match expressions where none of the expressions would match a given candidate, I decided to &#8230; <a href="http://www.pirrmann.net/pattern-matching-in-c-part-2/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>Last time, I just stopped before generating any real expression tree… Now is the perfect time to continue the process !</p>
<p>In order to handle match expressions where none of the expressions would match a given candidate, I decided to use an option type. This allows the generation of this type of expressions:</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">Func&lt;double, Option&lt;double&gt;&gt; matchSomeOrNone =
    (double d) =&gt;
        (d &gt; 0.0)
        ? Option&lt;double&gt;.Some(d)
        : Option&lt;double&gt;.None();</pre>
<p>Given this these options, the translation of last time’s sample code:</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">var stringPattern = PatternMatcher
    .CreateSwitch&lt;string, double&gt;()
    .Case("TEST"                        , s =&gt; Math.PI)
    .Case("TEST_1"                      , s =&gt; Math.E)
    .Case((string)null                  , s =&gt; 0.0)
    .Case(s =&gt; s.StartsWith("TEST__")   , s =&gt; Math.E * 2)
    .CaseElse(                            s =&gt; s.Length);</pre>
<p>would become:</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">Func&lt;string, Option&lt;double&gt;&gt; generatedFuncOption =
    (string s) =&gt;
        (s == "TEST")
            ? Option&lt;double&gt;.Some(Math.PI)
            : (s == "TEST_1")
                ? Option&lt;double&gt;.Some(Math.E)
                : (s == null)
                    ? Option&lt;double&gt;.Some(0.0)
                    : s.StartsWith("TEST__")
                        ? Option&lt;double&gt;.Some(Math.E * 2)
                        : Option&lt;double&gt;.Some(s.Length);</pre>
<p>In order to instantiate option types in LINQ expressions, I have to use the corresponding MethodInfo instances, obtained from reflexion :</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">MethodInfo createSomeMethodInfo =
    typeof(Option&lt;TResult&gt;)
        .GetMethod(
            "Some",
            BindingFlags.Public | BindingFlags.Static);

MethodInfo createNoneMethodInfo =
    typeof(Option&lt;TResult&gt;)
        .GetMethod(
            "None",
            BindingFlags.Public | BindingFlags.Static);</pre>
<p>And then, in order to finally build a matching expression, I loop over the match conditions and result selector expressions the following way:</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">private Func&lt;TSource, Option&lt;TResult&gt;&gt; BuildPatternMatchingFunc()
{
    ParameterExpression parameter =
        Expression.Parameter(typeof(TSource));

    Expression noneExpression = Expression.Call(
        createNoneMethodInfo);

    Expression caseExpression = noneExpression;

    foreach (var matchCase in this.cases.Reverse())
    {
        caseExpression =
            Expression.Condition(
                Expression.Invoke(
                    matchCase.TestExpression,
                    parameter),
                Expression.Call(
                    createSomeMethodInfo,
                    Expression.Invoke(
                        matchCase.SelectorExpression,
                        parameter)),
                caseExpression);
    }

    return Expression
        .Lambda&lt;Func&lt;TSource, Option&lt;TResult&gt;&gt;&gt;(
            caseExpression,
            parameter)
        .Compile();
}</pre>
<p>The createNoneMethodInfo and createSomeMethodInfo are the MethodInfo corresponding to the generic <em>Option&lt;T&gt;.None()</em> and <em>Option&lt;T&gt;.Some()</em> methods obtained by reflection.</p>
<p>Debugging this kind of expression building can be complicated, particularly without the ability to visualize clearly the expression tree… Hopefully, <a href="http://www.pirrmann.net/linq-provider-an-attempt-part-5/">I have built an expression tree visualizer in the past</a> (I could also have used the easy path and install <a href="http://blogs.msdn.com/b/charlie/archive/2008/02/13/linq-farm-seed-using-the-expression-tree-visualizer.aspx">the classical one</a>) ! From the C# sample again, I can produce the following expression tree:</p>
<div class="syntaxtree" style="margin-bottom: 15px; border-top: black 1px solid; height: 630px; border-right: black 1px solid; overflow-x: auto; overflow-y: hidden; border-bottom: black 1px solid; border-left: black 1px solid">
<div style="width: 2800px">
<ul>
<li><a href="#"><span class="node-name">IIF</span><br />Conditional</a>
<ul>
<li><a href="#"><span class="node-name">Invoke</span><br /><span class="node-type">Boolean</span><br /></a>
<ul>
<li><a href="#"><span class="node-name">Lambda</span><br /><span class="node-type">Func&lt;String, Boolean&gt;</span><br />x =&gt; (x == &#8220;TEST&#8221;)</a>
<li><a href="#"><span class="node-name">Parameter</span><br /><span class="node-type">String</span><br /></a></li>
</ul>
<li><a href="#"><span class="node-name">Call</span><br /><span class="node-type">Option&lt;Double&gt;</span><br />Some</a>
<ul>
<li><a href="#"><span class="node-name">Invoke</span><br /><span class="node-type">Double</span><br /></a>
<ul>
<li><a href="#"><span class="node-name">Lambda</span><br /><span class="node-type">Func&lt;String, Double&gt;</span><br />s =&gt; 3,14159265358979</a>
<li><a href="#"><span class="node-name">Parameter</span><br /><span class="node-type">String</span><br /></a></li>
</ul>
</li>
</ul>
<li><a href="#"><span class="node-name">IIF</span><br />Conditional</a>
<ul>
<li><a href="#"><span class="node-name">Invoke</span><br /><span class="node-type">Boolean</span><br /></a>
<ul>
<li><a href="#"><span class="node-name">Lambda</span><br /><span class="node-type">Func&lt;String, Boolean&gt;</span><br />x =&gt; (x == &#8220;TEST_1&#8243;)</a>
<li><a href="#"><span class="node-name">Parameter</span><br /><span class="node-type">String</span><br /></a></li>
</ul>
<li><a href="#"><span class="node-name">Call</span><br /><span class="node-type">Option&lt;Double&gt;</span><br />Some</a>
<ul>
<li><a href="#"><span class="node-name">Invoke</span><br /><span class="node-type">Double</span><br /></a>
<ul>
<li><a href="#"><span class="node-name">Lambda</span><br /><span class="node-type">Func&lt;String, Double&gt;</span><br />s =&gt; 2,71828182845905</a>
<li><a href="#"><span class="node-name">Parameter</span><br /><span class="node-type">String</span><br /></a></li>
</ul>
</li>
</ul>
<li><a href="#"><span class="node-name">IIF</span><br />Conditional</a>
<ul>
<li><a href="#"><span class="node-name">Invoke</span><br /><span class="node-type">Boolean</span><br /></a>
<ul>
<li><a href="#"><span class="node-name">Lambda</span><br /><span class="node-type">Func&lt;String, Boolean&gt;</span><br />s =&gt; (Convert(s) == null)</a>
<li><a href="#"><span class="node-name">Parameter</span><br /><span class="node-type">String</span><br /></a></li>
</ul>
<li><a href="#"><span class="node-name">Call</span><br /><span class="node-type">Option&lt;Double&gt;</span><br />Some</a>
<ul>
<li><a href="#"><span class="node-name">Invoke</span><br /><span class="node-type">Double</span><br /></a>
<ul>
<li><a href="#"><span class="node-name">Lambda</span><br /><span class="node-type">Func&lt;String, Double&gt;</span><br />s =&gt; 0</a>
<li><a href="#"><span class="node-name">Parameter</span><br /><span class="node-type">String</span><br /></a></li>
</ul>
</li>
</ul>
<li><a href="#"><span class="node-name">IIF</span><br />Conditional</a>
<ul>
<li><a href="#"><span class="node-name">Invoke</span><br /><span class="node-type">Boolean</span><br /></a>
<ul>
<li><a href="#"><span class="node-name">Lambda</span><br /><span class="node-type">Func&lt;String, Boolean&gt;</span><br />s =&gt; s.StartsWith(&#8220;TEST__&#8221;)</a>
<li><a href="#"><span class="node-name">Parameter</span><br /><span class="node-type">String</span><br /></a></li>
</ul>
<li><a href="#"><span class="node-name">Call</span><br /><span class="node-type">Option&lt;Double&gt;</span><br />Some</a>
<ul>
<li><a href="#"><span class="node-name">Invoke</span><br /><span class="node-type">Double</span><br /></a>
<ul>
<li><a href="#"><span class="node-name">Lambda</span><br /><span class="node-type">Func&lt;String, Double&gt;</span><br />s =&gt; 5,43656365691809</a>
<li><a href="#"><span class="node-name">Parameter</span><br /><span class="node-type">String</span><br /></a></li>
</ul>
</li>
</ul>
<li><a href="#"><span class="node-name">IIF</span><br />Conditional</a>
<ul>
<li><a href="#"><span class="node-name">Invoke</span><br /><span class="node-type">Boolean</span><br /></a>
<ul>
<li><a href="#"><span class="node-name">Lambda</span><br /><span class="node-type">Func&lt;String, Boolean&gt;</span><br />s =&gt; True</a>
<li><a href="#"><span class="node-name">Parameter</span><br /><span class="node-type">String</span><br /></a></li>
</ul>
<li><a href="#"><span class="node-name">Call</span><br /><span class="node-type">Option&lt;Double&gt;</span><br />Some</a>
<ul>
<li><a href="#"><span class="node-name">Invoke</span><br /><span class="node-type">Double</span><br /></a>
<ul>
<li><a href="#"><span class="node-name">Lambda</span><br /><span class="node-type">Func&lt;String, Double&gt;</span><br />s =&gt; Convert(s.Length)</a>
<li><a href="#"><span class="node-name">Parameter</span><br /><span class="node-type">String</span><br /></a></li>
</ul>
</li>
</ul>
<li><a href="#"><span class="node-name">Call</span><br /><span class="node-type">Option&lt;Double&gt;</span><br />None</a>
<ul></ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<p>This tree may seem wide, but is is just a succession of conditional expressions… Finally, the the function that evaluates the result of the pattern-matching expression is the following one:</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">public TResult Eval(TSource candidate)
{
    if (this.patternMatchingFunc == null)
    {
        this.patternMatchingFunc = BuildPatternMatchingFunc();
    }

    Option&lt;TResult&gt; matchResult = patternMatchingFunc
                                    .Invoke(candidate);

    if (!matchResult.IsSome)
        throw new NoMatchFoundException();

    return matchResult.Value;
}</pre>
<p>As you can see, it’s a wrapper around the expression evaluation invocation. It first generates the expression&nbsp; instantiates upon the first call (in a non-threadsafe way, but who cares !) and handles “nothing matches” case by throwing an exception. And this works !</p>
<p>Now, you might say that matching a single value in of very limited interest. I can’t deny it. Why don’t we try to match several values, then ?</p>
<img src="http://feeds.feedburner.com/~r/pirrmann/~4/W6liSlagDU0" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.pirrmann.net/pattern-matching-in-c-part-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.pirrmann.net/pattern-matching-in-c-part-2/</feedburner:origLink></item>
		<item>
		<title>Pattern matching in C# – part 1</title>
		<link>http://feedproxy.google.com/~r/pirrmann/~3/hJWdFl47or8/</link>
		<comments>http://www.pirrmann.net/pattern-matching-in-c-sharp-part-1/#comments</comments>
		<pubDate>Wed, 27 Feb 2013 20:44:11 +0000</pubDate>
		<dc:creator>Pierre IRRMANN</dc:creator>
				<category><![CDATA[Functional Inspiration]]></category>
		<category><![CDATA[Syntax Puzzles]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[Puzzle]]></category>

		<guid isPermaLink="false">http://www.pirrmann.net/?p=192</guid>
		<description><![CDATA[In my previous post, I tried to explain what pattern matching is, and in particular the F# match expression, that I’m trying to mimic in C#. For my first attempt, I’ll try to analyse the matching cases that can apply &#8230; <a href="http://www.pirrmann.net/pattern-matching-in-c-sharp-part-1/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>In my <a href="http://www.pirrmann.net/pattern-matching-in-c-sharp-introduction/">previous post</a>, I tried to explain what pattern matching is, and in particular the F# match expression, that I’m trying to mimic in C#. For my first attempt, I’ll try to analyse the matching cases that can apply on a single value. Let’s start right now with an F# sample<sup><a href="#note1">[1]</a></sup>:</p>
<pre class="brush: fsharp; gutter: false; toolbar: false;">let test str =
    match str with
    | "TEST" -&gt; Math.PI
    | "TEST_1" -&gt; Math.E
    | null -&gt; 0.0
    | s when s.StartsWith("TEST__") -&gt; Math.E * 2.0
    | s -&gt; float s.Length</pre>
<p>If we analyse these patterns, we see 3 different cases:</p>
<ul>
<li>a constant pattern (including the null value),
<li>a conditional pattern (the lambda one)
<li>a default pattern (the else case).</li>
</ul>
<p>So in C#, what I’ve managed to build is the following:</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">var stringPattern = PatternMatcher
.CreateSwitch&lt;string, double&gt;()
.Case("TEST"                        , s =&gt; Math.PI)
.Case("TEST_1"                      , s =&gt; Math.E)
.Case((string)null                  , s =&gt; 0.0)
.Case(s =&gt; s.StartsWith("TEST__")   , s =&gt; Math.E * 2)
.CaseElse(                            s =&gt; s.Length);</pre>
<p>What is difficult here is to write something that is valid C#, because:</p>
<ol>
<li>I can’t change the compiler,
<li>To keep things simple, I don’t want to use Roslyn in the first attempt (although that might come later).</li>
</ol>
<h3>Recording expressions for individual tests</h3>
<p>This solution is mainly based upon a generic class called <em>PatternMatcher&lt;TSource, TResult&gt;</em>, which represents the match expression being built. Each <em>Case</em> overload builds an instance of a <em>MatchCase</em> class. As with many “fluent” syntax nowadays, in order to chain the calls in a single statement, each <em>Case</em> overload returns a new instance of the <em>PatternMatcher</em>, which keeps track of all the cases registered so far.</p>
<p>The <em>MatchCase</em>’s sole purpose is to encapsulate two expressions:</p>
<ul>
<li>a test expression that will be used to determine if a particular source value matches the case: this will be an expression of <em>Func&lt;TSource, bool&gt;</em>,
<li>a selector expression that will be used to produce the result of the match expression when the input value matches this particular case: this will be an expression of <em>Func&lt;TSource, TResult&gt;</em>.</li>
</ul>
<p>Getting an Expression of a given Func type is nothing more that changing the type of a variable. The compiler will change its work accordingly, and produce an Expression from a given lambda-expression, instead of a typed delegate.</p>
<p>The most general case is the conditional pattern. Let’s take a look at the following extension method:</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">public static PatternMatcher&lt;TSource, TResult&gt;
    Case&lt;TSource, TResult&gt;(
        this PatternMatcher&lt;TSource, TResult&gt; pattern,
        Expression&lt;Func&lt;TSource, bool&gt;&gt; testExpression,
        Expression&lt;Func&lt;TSource, TResult&gt;&gt; selector)</pre>
<p>You can see that the testExpression and selector parameters are already the types that my <em>MatchCase</em> class needs. From this values, I just have to instantiate the class and store it for later use.</p>
<p>The two other&nbsp; cases (constant and default) will also provide directly the selector expression, only the test expression will have to be provided:</p>
<ul>
<li>as an expression that tests equality with a given constant, for the constant pattern,
<li>as an expression that is always true, for the default pattern.</li>
</ul>
<p>These cases are just special cases of the previous one, called with an appropriate lambda, which will be converted to the test expression.</p>
<h3>Building an expression tree</h3>
<p>Of course, what we want to do is more that just record the expressions ! The next step is to combine them in a global match expression.</p>
<p>The kind of code I would like to produce, for the previous sample, would be the following:</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">Func&lt;string, double&gt; generatedFunc =
(string s) =&gt;
    {
        if (s == "TEST") return Math.PI;
        if (s == "TEST_1") return Math.E;
        if (s == null) return 0.0;
        if (s.StartsWith("TEST__")) return Math.E * 2;
        return s.Length;
    };</pre>
<p>Or even “better”, the same, but with conditional expressions instead of <em>if</em> and <em>return</em> statements:</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">Func&lt;string, double&gt; generatedFuncNoIf =
    (string s) =&gt;
        (s == "TEST")
            ? Math.PI
            : (s == "TEST_1")
                ? Math.E
                : (s == null)
                    ? 0.0
                    : s.StartsWith("TEST__")
                        ? Math.E * 2
                        : s.Length;</pre>
<p>An expression corresponding to the previous code could be generated, but I also want to handle an additional case: when there is no match. This means that my expression has to be able to return some result or… none. <a href="http://www.pirrmann.net/functional-inspiration-a-simple-option-type/">Some or none ? Isn’t there a type for that ?</a> We’ll see how to use it next time.</p>
<p><a name="note1">[1]</a> I know this sample is useless and theoretical, but isn’t this whole series ? If you really want to use match expressions, embrace F#, not C# !</p>
<img src="http://feeds.feedburner.com/~r/pirrmann/~4/hJWdFl47or8" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.pirrmann.net/pattern-matching-in-c-sharp-part-1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.pirrmann.net/pattern-matching-in-c-sharp-part-1/</feedburner:origLink></item>
		<item>
		<title>Pattern matching in C# – introduction</title>
		<link>http://feedproxy.google.com/~r/pirrmann/~3/iGz7lNhlyec/</link>
		<comments>http://www.pirrmann.net/pattern-matching-in-c-sharp-introduction/#comments</comments>
		<pubDate>Wed, 27 Feb 2013 06:06:24 +0000</pubDate>
		<dc:creator>Pierre IRRMANN</dc:creator>
				<category><![CDATA[Functional Inspiration]]></category>
		<category><![CDATA[Syntax Puzzles]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[Puzzle]]></category>

		<guid isPermaLink="false">http://www.pirrmann.net/?p=190</guid>
		<description><![CDATA[Although bringing real pattern matching to C# in not my objective, I’ve tackled yet another syntax puzzle, trying to build a “sort-of” F#-ish pattern-matching-like syntax. Disclaimer : as you can see from the quotes and italic, don’t expect me to &#8230; <a href="http://www.pirrmann.net/pattern-matching-in-c-sharp-introduction/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>Although bringing real pattern matching to C# in not my objective, I’ve tackled yet another syntax puzzle, trying to build a <em>“sort-of” F#-ish pattern-matching-like</em> syntax.<br /> <u>Disclaimer : as you can see from the quotes and italic, don’t expect me to build a fully-functional F# pattern matching in C#.</u></p>
<h3>What is pattern matching ?</h3>
<p>From the <a href="http://msdn.microsoft.com/en-us/library/dd547125.aspx">MSDN entry on Pattern matching</a> :</p>
<blockquote><p>Patterns are rules for transforming input data. They are used throughout the F# language to compare data with a logical structure or structures, decompose data into constituent parts, or extract information from data in various ways.</p>
</blockquote>
<p>The point I want to focus on is in fact the <a href="http://msdn.microsoft.com/en-us/library/dd233242.aspx">F# match expression</a>. The match expression is a powerful way to express conditions over data. It is often described as a “switch statement on steroids”. Its characteristics are the following :</p>
<ul>
<li>Just like a switch, it takes a value as its input,
<li>Unlike a switch, the value is not limited only to enums or built-in value types.
<li>It has a return type. If there is nothing to return, F# uses a special <em>unit</em> type, but there is no <em>void</em> as a return type neither a <em>null</em> value.
<li>If the values to return can be of different types depending on the input, Discriminated Unions (DUs) can be used as return types. </li>
</ul>
<p>I’ll start with a simple F# sample, to show what a discriminated union is :</p>
<pre class="brush: fsharp; gutter: false; toolbar: false;">type Shape =
    | Point
    | Circle of float
    | Rectangle of float * float</pre>
<p>In this sample, a type Shape is defined, that can be either a Point, a Circle or a Rectangle. Although the Point could be considered a simple enum value, the Circle and Rectangle cases, unlike enums, carry data. For instance :</p>
<pre class="brush: fsharp; gutter: false; toolbar: false;">let p = Point
let c = Circle(5.0)
let r = Rectangle(10.0, 20.0)</pre>
<p>If we want to extract the data components of a particular union type, we use pattern-matching in the following way :</p>
<pre class="brush: fsharp; gutter: false; toolbar: false;">let Rectangle(w, h) = r</pre>
<p>This expression binds the value of w and h to the data elements of the r Rectangle defined earlier. But my purpose in the blog series is to introduce in C# a syntax that would look like a match expression, which in F# is the following :</p>
<pre class="brush: fsharp; gutter: false; toolbar: false;">let getArea s =
    match s with
    | Point -&gt; 0.0
    | Circle(r) -&gt; r * r * System.Math.PI
    | Rectangle(w, h) -&gt; w * h</pre>
<p>In this attempt, I first consider matching simple values (which has no practical interest of any sort), then matching tuples, and I’ll finish with matching against some sort of Discriminated Union, although DUs are not a native C# construct.</p>
<p>First, let’s consider what we want to build. From the sample above, we can see that what we get from the match expression is a “<em>getArea</em>” that takes an instance of the union type as input, and gives a float as output. As this is just the definition of a function, it looks like we’re trying to build a construct that generates instances of the generic <em>Func&lt;TInput, TOutput&gt;</em> delegate.</p>
<p>In F#, match expressions can also be used to perform actions, and in this case will return the special <em>unit</em> type. To perform actions in C# we have the <em>Action&lt;T&gt;</em> delegate type. In this series I’ll consider only the functions, but actions could be built exactly the same way.</p>
<p>In <a href="http://www.pirrmann.net/pattern-matching-in-c-sharp-part-1/">the next part</a>, I’ll show my first naive attempt to deal with simple values, before targeting any tuples or discriminated union types.</p>
<img src="http://feeds.feedburner.com/~r/pirrmann/~4/iGz7lNhlyec" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.pirrmann.net/pattern-matching-in-c-sharp-introduction/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.pirrmann.net/pattern-matching-in-c-sharp-introduction/</feedburner:origLink></item>
		<item>
		<title>Functional Inspiration – A simple Option type</title>
		<link>http://feedproxy.google.com/~r/pirrmann/~3/cCDVbM87ZLM/</link>
		<comments>http://www.pirrmann.net/functional-inspiration-a-simple-option-type/#comments</comments>
		<pubDate>Tue, 26 Feb 2013 06:03:22 +0000</pubDate>
		<dc:creator>Pierre IRRMANN</dc:creator>
				<category><![CDATA[Functional Inspiration]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[F#]]></category>

		<guid isPermaLink="false">http://www.pirrmann.net/?p=189</guid>
		<description><![CDATA[In F#, the option type is a built-in Discriminated Union type which allows to handle nicely the fact that an expression can represent some value or none. In C#, we have almost this construct when we use the Nullable&#60;T&#62;, but &#8230; <a href="http://www.pirrmann.net/functional-inspiration-a-simple-option-type/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>In F#, the option type is a built-in Discriminated Union type which allows to handle nicely the fact that an expression can represent some value or none. In C#, we have almost this construct when we use the Nullable&lt;T&gt;, but as I’ve already stated before, this type is available only for value types. Here is an option type that deals also with reference types.</p>
<p>I’ve already played with an Irreleventable&lt;T&gt; type in the past, and the implementation of it is quite the same as what I’ll do today, but the semantics are different, and I don’t want to re-use this type in a misleading way.</p>
<p>So today, I bring you “yet another option type” in C# :</p>
<div class="small-code">
<pre class="brush: csharp; gutter: false; toolbar: false;">public struct Option&lt;T&gt;
{
    private readonly bool isSome;
    public bool IsSome
    {
        get
        {
            return isSome;
        }
    }

    private readonly T value;
    public T Value
    {
        get
        {
            if (!isSome) throw new NotSupportedException();
            return value;
        }
    }

    private Option(bool isSome, T value)
    {
        this.isSome = isSome;
        this.value = value;
    }

    public static Option&lt;T&gt; Some(T value)
    {
        return new Option&lt;T&gt;(true, value);
    }

    public static Option&lt;T&gt; None()
    {
        return new Option&lt;T&gt;(false, default(T));
    }

    public override int GetHashCode()
    {
        return isSome
            ? value.GetHashCode()
            : -1;
    }

    public override bool Equals(object other)
    {
        if (!(other is Option&lt;T&gt;))
            return false;

        Option&lt;T&gt; otherOption = (Option&lt;T&gt;)other;

        return IsSome
            ? (value == null &amp;&amp; otherOption.Value == null)
                || value.Equals(otherOption.Value)
            : !otherOption.IsSome;
    }

    public override string ToString()
    {
        return this.IsSome
            ? this.value.ToString()
            : String.Empty;
    }
}</pre>
</div>
<p>The only noticeable differences with the Irreleventable type are the (chosen) lack of conversion operators, and the equality comparison, as an Option&lt;T&gt; will never be considered equal to an instance of T (unlike the Irreleventable).</p>
<p>Why would I write a blog post simply to introduce this type, without any context ? More to come soon.</p>
<img src="http://feeds.feedburner.com/~r/pirrmann/~4/cCDVbM87ZLM" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.pirrmann.net/functional-inspiration-a-simple-option-type/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.pirrmann.net/functional-inspiration-a-simple-option-type/</feedburner:origLink></item>
		<item>
		<title>Elitism ? Or just raising the bar ?</title>
		<link>http://feedproxy.google.com/~r/pirrmann/~3/b9icNQQmMAA/</link>
		<comments>http://www.pirrmann.net/elitism-or-just-raising-the-bar/#comments</comments>
		<pubDate>Sat, 26 Jan 2013 10:07:30 +0000</pubDate>
		<dc:creator>Pierre IRRMANN</dc:creator>
				<category><![CDATA[Practices]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Pragmatism]]></category>
		<category><![CDATA[Software Craftsmanship]]></category>

		<guid isPermaLink="false">http://www.pirrmann.net/?p=185</guid>
		<description><![CDATA[Last Thursday, I’ve attended an open forum organised by ALT.NET France user group, about the Software Craftsmanship Community and the “Fier d’être développeur” (“Proud to be dev”) groups, in order to compare their intents and try to explain why they &#8230; <a href="http://www.pirrmann.net/elitism-or-just-raising-the-bar/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>Last Thursday, I’ve attended an open forum organised by <a href="http://www.meetup.com/altnetfr/">ALT.NET France user group</a>, about the <a href="http://www.meetup.com/paris-software-craftsmanship/">Software Craftsmanship Community</a> and the “<a href="http://fierdetredeveloppeur.org/">Fier d’être développeur</a>” (“Proud to be dev”) groups, in order to compare their intents and try to explain why they exist and what they try to achieve.</p>
<p>One of the questions that was raised during the evening was the following : Is the “Software Craftsmanship” movement elitist or is it a way to democratize good practices ? After a great deal of discussion, we agreed on the fact that it can be seen the both ways. Let’s face it : we meet in the evening to talk about programming… We’re part of the “10 percent alpha-geeks”. And yes, there is some kind of elitism about it.</p>
<p>On one hand, to someone that comes for the first time, all the practices, languages and tools we talk about might seem too complex, and frighten him (or her). On the other hand, realizing that there are so many things that we don’t know is the first step to getting better, isn’t it ? To my mind, this whole question of “raising the bar” instead of letting the average level go low, is not specific to programming but is true for any kind of teaching/learning topic. What makes it so important in programming is that we can’t stop learning during our career, if we want to stay up-to-date…</p>
<p>But if our goal is to “raise the bar”, how do we do it on a day-to-day basis ? If we want to show our colleagues some tricks, so that they ask for more, not that they run away…</p>
<p>Let’s illustrate that with an example from real life. A couple days ago I wanted extract from several data series the dates that were common to all these series. This might seem quite simple, but there are numerous ways to do that, and I find it a good case study of how to balance readability and (perceived) complexity…</p>
<p><em>&lt;YAK-SHAVING&gt;My Visual Studio 2012 RC has expired… I’m switching to MonoDevelop in order to write my sample code…&lt;/YAK-SHAVING&gt;</em></p>
<p>Let&#8217;s consider several collections of points, where a point is simply a date and a decimal value :</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">public class Point
{
    public DateTime Date { get; set; }
    public decimal Value { get; set; }
}</pre>
<p>And now imagine that I have a collection of series of points, represented as such :</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">IEnumerable&lt;IEnumerable&lt;Point&gt;&gt; series</pre>
<p>Now the point is to get the dates that are common to all these series. With a straight implementation, this could go this way :</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">[Test()]
public void TestStraightLoops()
{
    IEnumerable&lt;IEnumerable&lt;Point&gt;&gt; series =
        DataSeries.GetSeries(2013);

    List&lt;DateTime&gt; commonDates = new List&lt;DateTime&gt; ();
    bool first = true;
    foreach (var serie in series)
    {
        if(first)
        {
            foreach(var point in serie)
            {
                commonDates.Add(point.Date);
            }
        }
        else
        {
            List&lt;DateTime&gt; datesToRemove = new List&lt;DateTime&gt;();
            foreach(var commonDate in commonDates)
            {
                bool found = false;
                foreach(var point in serie)
                {
                    if(commonDate == point.Date)
                    {
                        found = true;
                        break;
                    }
                }

                if(!found)
                {
                    datesToRemove.Add(commonDate);
                }
            }

            foreach(var dateToRemove in datesToRemove)
            {
                commonDates.Remove(dateToRemove);
            }
        }
        first = false;
    }

    Assert.AreEqual(76, commonDates.Count);
}</pre>
<p>OK, this works. How long does it take to read it and understand it ? What if, instead, I chose to use my basic knowledge of LINQ ? I’ll skip a few steps, but what if came up with this :</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">[Test()]
public void TestForEachIntersect ()
{
    IEnumerable&lt;IEnumerable&lt;Point&gt;&gt; series =
        DataSeries.GetSeries(2013);

    IEnumerable&lt;DateTime&gt; commonDates = null;

    foreach (var serie in series)
    {
        var dates = serie.Select(p =&gt; p.Date);

        commonDates = (commonDates == null)
            ? dates
            : commonDates.Intersect(dates);
    }

    Assert.AreEqual(76, commonDates.Count());
}</pre>
<p>This is obviously shorter. Is it more or less difficult to read and maintain ? Should I stop here ? What if wrote the following, using Aggregate to do the same thing as above, but inside an extension method ?</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">public static IEnumerable&lt;TResult&gt; IntersectMany&lt;T, TResult&gt;
    (this IEnumerable&lt;IEnumerable&lt;T&gt;&gt; source,
     Func&lt;T, TResult&gt; selector)
{
    return source.Aggregate(
        (IEnumerable&lt;TResult&gt;)null,
        (a, s) =&gt; a == null
                ? s.Select(selector)
                : a.Intersect(s.Select(selector)));

}</pre>
<p>Obviously this method is less readable… But the consumer code is now the following :</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">[Test()]
public void TestIntersectMany()
{
    IEnumerable&lt;IEnumerable&lt;Point&gt;&gt; series =
        DataSeries.GetSeries(2013);
    
    var commonDates = series
        .IntersectMany(p =&gt; p.Date);
    
    Assert.AreEqual(76, commonDates.Count());
}</pre>
<p>And… I kind of like the expressiveness of it. So where must we stop ? To my mind, we must stop when it can be maintained. Aren’t we <a href="http://pragprog.com/the-pragmatic-programmer">pragmatic programmers</a>, after all ?</p>
<p>I think that Software Craftsmanship is very well summed-up in <a href="https://twitter.com/sandromancuso">Sandro Mancuso</a>’s book title : “<a href="https://leanpub.com/socra">Software Craftsmanship : Professionalism, Pragmatism, Pride</a>”. Those words are in the right order. Pride is part of it, but it come only third.</p>
<img src="http://feeds.feedburner.com/~r/pirrmann/~4/b9icNQQmMAA" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.pirrmann.net/elitism-or-just-raising-the-bar/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.pirrmann.net/elitism-or-just-raising-the-bar/</feedburner:origLink></item>
		<item>
		<title>RPSLS — Rock Paper Scissors Lizard Spock</title>
		<link>http://feedproxy.google.com/~r/pirrmann/~3/8CpmQpCRVbg/</link>
		<comments>http://www.pirrmann.net/rpsls-rock-paper-scissors-lizard-spock/#comments</comments>
		<pubDate>Thu, 22 Nov 2012 21:35:11 +0000</pubDate>
		<dc:creator>Pierre IRRMANN</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.pirrmann.net/?p=180</guid>
		<description><![CDATA[Let’s start with a tweet from earlier today : Anyone bored and have an android phone?play.google.com/store/apps/det… — Leonard Hofstadter (@TheRealLeonardH) November 22, 2012 If you follow the link, you&#8217;ll get to a Google Play application that allows you to play &#8230; <a href="http://www.pirrmann.net/rpsls-rock-paper-scissors-lizard-spock/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>Let’s start with a tweet from earlier today :</p>
<blockquote lang="fr" class="twitter-tweet"><p>Anyone bored and have an android phone?<a title="https://play.google.com/store/apps/details?id=cc.spock.ui" href="https://t.co/iUYY4xYK">play.google.com/store/apps/det…</a></p>
<p>— Leonard Hofstadter (@TheRealLeonardH) <a href="https://twitter.com/TheRealLeonardH/status/271551511631376384">November 22, 2012</a></p></blockquote>
<p><img style="float: right; display: inline" align="right" src="http://www.pirrmann.net/wp-content/uploads/2012/09/geek-gestures-rpsls.jpg">If you follow the link, you&#8217;ll get to a Google Play application that allows you to play the (in-)famous <a href="http://en.wikipedia.org/wiki/Rock-paper-scissors-lizard-Spock" target="_blank">RPSLS (Rock-paper-scissors-lizard-Spock)</a> game. Why that tweet stroke me is that I had already played (with code !) around that game a few months ago…</p>
<p>Although this is just a variant of the classical rock-paper-scissors game, the two additional gestures shift the number of gesture combinations to 25, as shown on this matrix:</p>
<p><img src="http://www.pirrmann.net/wp-content/uploads/2012/11/Normal_form_matrix_of_Rock-paper-scissors-lizard-Spock.jpg"></p>
<p><font size="1">(image taken from </font><a title="http://en.wikipedia.org/wiki/File:Normal_form_matrix_of_Rock-paper-scissors-lizard-Spock.jpg" href="http://en.wikipedia.org/wiki/File:Normal_form_matrix_of_Rock-paper-scissors-lizard-Spock.jpg"><font size="1">http://en.wikipedia.org/wiki/File:Normal_form_matrix_of_Rock-paper-scissors-lizard-Spock.jpg</font></a><font size="1">)</font></p>
<p>There could be several ways to test these different combinations, for instance using the previous matrix as a reference, but… come on…. a closed set of values, and a simple behaviour… That’s just a perfect candidate for an enum ! And the best part is that I have actually implemented this as a test two months ago (<a href="https://github.com/pirrmann/PolymorphicEnum/commit/f5e0a18fa2df12f95cfa06f31efe44aa16a67a1e" target="_blank">proof on Github !</a>).</p>
<p>Let’s first define the possible game outcomes :</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">public class GameOutcome : PolymorphicEnum&lt;GameOutcome&gt;
{
    public static GameOutcome WIN = Register();
    public static GameOutcome LOSE = Register();
    public static GameOutcome DRAW = Register();
}</pre>
<p>Then we define the Gesture class and its values :</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">public class GeekGesture : PolymorphicEnum&lt;GeekGesture&gt;
{
    public static GeekGesture ROCK = Register();
    public static GeekGesture PAPER = Register();
    public static GeekGesture SCISSORS = Register();
    public static GeekGesture SPOCK = Register();
    public static GeekGesture LIZARD = Register();
    [...]</pre>
<p>The trick here is that I changed the order of the values int the enum from Rock &#8211; paper &#8211; scissors &#8211; lizard &#8211; Spock to Rock &#8211; paper &#8211; scissors &#8211; Spock &#8211; lizard. This way, each values beats its predecessor and its second successor, and loses against its successor and second predecessor…</p>
<p>The behaviour can then be simply implemented based on the integer values of the enums :</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">// we can use the int representation and a modulo trick !
public GameOutcome PlayAgainst(GeekGesture other)
{
    return this == other
        ? GameOutcome.DRAW
        : (GameOutcome)(((other + 5 - this) % 5) % 2);
}</pre>
<p>Now we can write the tests in a very expressive way :</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">[TestMethod]
public void gesture_against_2nd_next_is_a_win()
{
    Assert.AreEqual(GameOutcome.WIN,
        GeekGesture.ROCK.PlayAgainst(GeekGesture.SCISSORS));
    Assert.AreEqual(GameOutcome.WIN,
        GeekGesture.PAPER.PlayAgainst(GeekGesture.SPOCK));
    Assert.AreEqual(GameOutcome.WIN,
        GeekGesture.SCISSORS.PlayAgainst(GeekGesture.LIZARD));
    Assert.AreEqual(GameOutcome.WIN,
        GeekGesture.SPOCK.PlayAgainst(GeekGesture.ROCK));
    Assert.AreEqual(GameOutcome.WIN,
        GeekGesture.LIZARD.PlayAgainst(GeekGesture.PAPER));
}
</pre>
<p>So… here is my answer to Leonard :</p>
<blockquote lang="fr" class="twitter-tweet" data-in-reply-to="271551511631376384">
<p>@<a href="https://twitter.com/therealleonardh">therealleonardh</a> I have and android phone, but when I’m bored I think about software, and sometimes blog about it : <a title="http://www.pirrmann.net/rpsls-rock-paper-scissors-lizard-spock/" href="http://t.co/EyihOhy1">pirrmann.net/rpsls-rock-pap…</a></p>
<p>— Pierre Irrmann (@pirrmann) <a href="https://twitter.com/pirrmann/status/271729506933415936" data-datetime="2012-11-22T21:38:57+00:00">November 22, 2012</a></p></blockquote>
<p><script src="//platform.twitter.com/widgets.js" charset="utf-8"></script></p>
<img src="http://feeds.feedburner.com/~r/pirrmann/~4/8CpmQpCRVbg" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.pirrmann.net/rpsls-rock-paper-scissors-lizard-spock/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.pirrmann.net/rpsls-rock-paper-scissors-lizard-spock/</feedburner:origLink></item>
		<item>
		<title>Cartesian products in LINQ (fluent syntax)</title>
		<link>http://feedproxy.google.com/~r/pirrmann/~3/Jetufq3EOdo/</link>
		<comments>http://www.pirrmann.net/cartesian-products-in-linq-fluent-syntax/#comments</comments>
		<pubDate>Thu, 01 Nov 2012 08:57:34 +0000</pubDate>
		<dc:creator>Pierre IRRMANN</dc:creator>
				<category><![CDATA[LINQ]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Extension Methods]]></category>

		<guid isPermaLink="false">http://www.pirrmann.net/?p=172</guid>
		<description><![CDATA[Have you ever tried to combines sequences in order to build Cartesian products in LINQ ? This is really easily achieved using the query expressions syntax, writing for instance : var ints = Enumerable.Range(1, 4); var longs = Enumerable.Range(1, 3).Select(i &#8230; <a href="http://www.pirrmann.net/cartesian-products-in-linq-fluent-syntax/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>Have you ever tried to combines sequences in order to build Cartesian products in LINQ ? This is really easily achieved using the query expressions syntax, writing for instance :</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">var ints = Enumerable.Range(1, 4);
var longs = Enumerable.Range(1, 3).Select(i =&gt; (long)i);

var products = from i in ints
    from l in longs
    select i * l;</pre>
<p>When I write LINQ queries, I tend to use more often the fluent syntax, as it is more powerful, and allows me to use a wider range of operators. I also try not to mix both syntaxes, because I find it quite confusing. When I want to perform, inside of a more complex query, a simple cross-product as the previous one, the “fluent” equivalent syntax is the following :</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">var products = ints.SelectMany(i =&gt; longs.Select(l =&gt; i * l));</pre>
<p>In fact, this syntax works very well, but I don&#8217;t find it as expressive as the first one. And if you go one step further and add a third sequence to the party…</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">var ints = Enumerable.Range(1, 4);
var longs = Enumerable.Range(1, 3).Select(i =&gt; (long)i);
var strings = new[] { "a", "b", "c" };

var classic = from i in ints
    from l in longs
    from s in strings
    select (i * l).ToString() + s;</pre>
<p>The “fluent” syntax gets even more confusing (at least to me) :</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">var fluent = ints.SelectMany(
    i =&gt; longs.SelectMany(
    l =&gt; strings.Select(s =&gt; (i * l).ToString() + s)));</pre>
<p>I think that what bothers me might be the ever-increasing number of unclosed parenthesis… Anyway, as usual, I played with extensions methods and here is what I came up with, using a new “Cross” method, for the 2 sequences cross-product :</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">var results = ints
    .Cross(longs)
    .Select((i, l) =&gt; i * l);</pre>
<p>And the same syntax for the 3 sequences cross product :</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">var results = ints
    .Cross(longs)
    .Cross(strings)
    .Select((i, l, s) =&gt; (i * l).ToString() + s);</pre>
<p>Don’t you find it more expressive ?</p>
<p>Finally, here are the extensions methods implementations :</p>
<div class="small-code">
<pre class="brush: csharp; gutter: false; toolbar: false;">public static IEnumerable&lt;Tuple&lt;TLeft, TRight&gt;&gt; Cross&lt;TLeft, TRight&gt;(
    this IEnumerable&lt;TLeft&gt; left, IEnumerable&lt;TRight&gt; right)
{
    return left.SelectMany(l =&gt; right.Select(r =&gt; Tuple.Create(l, r)));
}

public static IEnumerable&lt;Tuple&lt;TLeft1, TLeft2, TRight&gt;&gt; Cross&lt;TLeft1, TLeft2, TRight&gt;(
    this IEnumerable&lt;Tuple&lt;TLeft1, TLeft2&gt;&gt; left, IEnumerable&lt;TRight&gt; right)
{
    return left.SelectMany(l =&gt; right.Select(r =&gt; Tuple.Create(l.Item1, l.Item2, r)));
}

public static IEnumerable&lt;TResult&gt; Select&lt;T1, T2, TResult&gt;(
    this IEnumerable&lt;Tuple&lt;T1, T2&gt;&gt; source, Func&lt;T1, T2, TResult&gt; selector)
{
    return source.Select(t =&gt; selector(t.Item1, t.Item2));
}

public static IEnumerable&lt;TResult&gt; Select&lt;T1, T2, T3, TResult&gt;(
    this IEnumerable&lt;Tuple&lt;T1, T2, T3&gt;&gt; source, Func&lt;T1, T2, T3, TResult&gt; selector)
{
    return source.Select(t =&gt; selector(t.Item1, t.Item2, t.Item3));
}</pre>
</div>
<p>I must admit that those generic methods signatures are horrible, though…</p>
<img src="http://feeds.feedburner.com/~r/pirrmann/~4/Jetufq3EOdo" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.pirrmann.net/cartesian-products-in-linq-fluent-syntax/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.pirrmann.net/cartesian-products-in-linq-fluent-syntax/</feedburner:origLink></item>
		<item>
		<title>Polymorphic enums in C#, implementation revealed</title>
		<link>http://feedproxy.google.com/~r/pirrmann/~3/EjiqRghbwyk/</link>
		<comments>http://www.pirrmann.net/polymorphic-enums-in-c-sharp-implementation-revealed/#comments</comments>
		<pubDate>Sat, 29 Sep 2012 10:13:46 +0000</pubDate>
		<dc:creator>Pierre IRRMANN</dc:creator>
				<category><![CDATA[Syntax Puzzles]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Enum]]></category>
		<category><![CDATA[Polymorphism]]></category>
		<category><![CDATA[Puzzle]]></category>

		<guid isPermaLink="false">http://www.pirrmann.net/?p=167</guid>
		<description><![CDATA[How can we implement a polymorphic enum to mimic the Java ones ? In a previous post, as an answer to @cyriux’s one, I showed how we could try to use a polymorphic enum in C# in order to mimic &#8230; <a href="http://www.pirrmann.net/polymorphic-enums-in-c-sharp-implementation-revealed/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<h3>How can we implement a polymorphic enum to mimic the Java ones ?</h3>
<p>In a previous post, as an answer to @cyriux’s one, I showed how we could try to use a polymorphic enum in C# in order to mimic the Java ones. I have ported to C# the Java samples, using a base class called PolymorphicEnum. In this post, I’m going to give details about the implementation of this class.</p>
<p>The very first objectives are :</p>
<ol>
<li>To create an enum that derives from a base PolymorphicEnum.
<li>This derived enum must be able to define a set of values. </li>
</ol>
<h3>Getting started</h3>
<p><img style="display: block; float: none; margin-left: auto; margin-right: auto" src="http://www.pirrmann.net/wp-content/uploads/2012/09/step-1.png"></p>
<p>What I want to be able to write is something like :</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">public class SomeEnum : PolymorphicEnum
{
    public static SomeEnum FirstValue;
    public static SomeEnum SecondValue;
}</pre>
<p>As I can’t change the compiler behaviour, the two values declared in the previous sample must be instantiated somehow. The declaration then becomes :</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">public class SomeEnum : PolymorphicEnum
{
    public static SomeEnum FirstValue = Register();
    public static SomeEnum SecondValue = Register();
}</pre>
<p>In order to be able to write such code, here is what I can do :</p>
<ol>
<li>First, the class I want to define is only meant to be derived from, so it must be abstract. Therefore, it can only be a class, and not a struct. So I’ll have to override the Equals and GetHashCode methods in order to get a value comparison behaviour for two different instances of enums. But if the singleton-ness is implemented properly… I should never have two instances !
<li>The class will have a generic Ordinal read-only property, where T is a value type. If not provided, this type will be an int by default.
<li>In order to instantiate enum values, the base class will have to expose a static protected method “Register”. </li>
</ol>
<p>This leads us to this basic definition :</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">public abstract class PolymorphicEnum&lt;T&gt;
    where T : struct, IComparable&lt;T&gt;, IConvertible
{
    public T Ordinal { get; private set; }
    public string Name { get; private set; }

    protected PolymorphicEnum()
    {
    }

    public override string ToString()
    {
        return this.Name;
    }
}</pre>
<p>And in order to get an int as the default underlying type, we define a derived class :</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">public abstract class PolymorphicEnum : PolymorphicEnum&lt;int&gt;
{
}</pre>
<h3>Adding registration</h3>
<p><img style="display: block; float: none; margin-left: auto; margin-right: auto" src="http://www.pirrmann.net/wp-content/uploads/2012/09/step-2.png"></p>
<p>Ok, this has been quite simple. Now, we want the base class to allow its children to register instances. This means the base class will be responsible for instantiating, registering and tracking these instances. In order for the base class to instantiate the derived classes, we need to know their type in the method. To to this, we introduce a generic type parameter. We also want this method to accept an optional “ordinal” parameter, to handle the case where the ordinal values are defined by user-code. What we need is a method of the form :</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">protected static TEnumInstance Register&lt;TEnumInstance&gt;(
    Nullable&lt;T&gt; ordinal = null)
where TEnumInstance : new()</pre>
<p>Notice the “new()” generic constraint on the type parameter : the given type has to have a parameter-less constructor, which we’ll use to instantiate it. But as we go towards the polymorphic behaviour, the enum class that we’ll have to instantiate can be a sub-class from the actual enum type ! For instance, if we take the first sample from the previous post, we have the following inheritance :</p>
<p align="center"><img src="http://www.pirrmann.net/wp-content/uploads/2012/09/gesture-classes.png"></p>
<p>Because we do not want to give both of these type arguments on each Register call, the TEnum type argument moves up to the class level, and the class definition and Register method signature shift the following way:</p>
<div style="overflow-y: hidden; margin-bottom: 1.2em; overflow: auto">
<table style="border-right-width: 0px; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px">
<tbody>
<tr>
<td style="vertical-align: top">
<pre class="brush: csharp; gutter: false; toolbar: false;">public abstract class PolymorphicEnum&lt;T&gt;
    where T : struct, IComparable&lt;T&gt;, IConvertible&nbsp; </pre>
</td>
<td style="vertical-align: middle">=&gt;</td>
<td style="vertical-align: top">
<pre class="brush: csharp; gutter: false; toolbar: false;">public abstract class PolymorphicEnum&lt;T, TEnum&gt;
where T : struct, IComparable&lt;T&gt;, IConvertible
where TEnum : PolymorphicEnum&lt;T, TEnum&gt;, new()
</pre>
</td>
</tr>
<tr>
<td style="vertical-align: top">
<pre class="brush: csharp; gutter: false; toolbar: false;">protected static TEnumInstance Register&lt;TEnumInstance&gt;(
    Nullable&lt;T&gt; ordinal = null)
where TEnumInstance : new()</pre>
</td>
<td style="vertical-align: middle">=&gt;</td>
<td style="vertical-align: top">
<pre class="brush: csharp; gutter: false; toolbar: false;">protected static TEnum Register&lt;TEnumInstance&gt;(
    Nullable&lt;T&gt; ordinal = null)
where TEnumInstance : TEnum, new()
</pre>
</td>
</tr>
</tbody>
</table>
</div>
<p>The registration of the enum values is performed in a static dictionary, so here is at last the register method :</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">protected static TEnum Register&lt;TEnumInstance&gt;(
        Nullable&lt;T&gt; ordinal = null)
    where TEnumInstance : TEnum, new()
{
    if (!ordinal.HasValue)
    {
        ordinal = registeredInstances.Any()
            ? registeredInstances.Keys.Max().PlusOne()
            : default(T);
    }

    TEnum instance = new TEnumInstance();
    instance.Ordinal = ordinal.Value;

    registeredInstances.Add(ordinal.Value, instance);

    return instance;
}</pre>
<p>Comment : how to implement a “PlusOne” extension method, that could increment any of the underlying types supported by an enum, has been a puzzle of its own… <a href="http://www.pirrmann.net/polymorphic-enums-in-c-sharp-generic-incrementation/" target="_blank">See this post for my solution !</a></p>
<h3>Simplifying registration</h3>
<p><img style="display: block; float: none; margin-left: auto; margin-right: auto" src="http://www.pirrmann.net/wp-content/uploads/2012/09/step-3.png"></p>
<p>From now on we can register enum value the following way :</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">public class SomeEnum : PolymorphicEnum&lt;SomeEnum&gt;
{
    public static SomeEnum FirstValue = Register&lt;SomeEnum&gt;();
    public static SomeEnum SecondValue = Register&lt;SomeEnum&gt;();
}</pre>
<p>Wait !? Why must we provide the type to the Register method, if that is the same as the generic argument of the class ? Let’s move forward and define an additional Register method :</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">protected static TEnum Register(Nullable&lt;T&gt; ordinal = null)
{
    return Register&lt;TEnum&gt;(ordinal);
}</pre>
<p>And the registration gets simpler again :</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">public class SomeEnum : PolymorphicEnum&lt;SomeEnum&gt;
{
    public static SomeEnum FirstValue = Register();
    public static SomeEnum SecondValue = Register();
}</pre>
<h3>Finding the names</h3>
<p><img style="display: block; float: none; margin-left: auto; margin-right: auto" src="http://www.pirrmann.net/wp-content/uploads/2012/09/step-4.png"></p>
<p>So now we can register enum values, optionally specifying the ordinal value… but we’re not done yet ! I mean, aren’t we supposed to be able to convert enums from and to strings ? From the previous steps, we have a Name property with a private setter, and an overridden ToString() method. But the Name property is never set ! In my first implementations, providing the Register method with the string to associate with the value was mandatory. I was not satisfied with this solution, and I came up with the following replacement solution :</p>
<ol>
<li>I added a static field to the class :
<pre class="brush: csharp; gutter: false; toolbar: false;">private static bool namesInitialized = false;</pre>
<li>I replaced the Name property implementation with this new one :
<pre class="brush: csharp; gutter: false; toolbar: false;">private string name = null;
private string Name
{
    get
    {
        EnsureNamesInitialized();
        return this.name;
    }
    set
    {
        this.name = value;
    }
}</pre>
<li>I implemented the EnsureNamesInitialized method :
<pre class="brush: csharp; gutter: false; toolbar: false;">protected void EnsureNamesInitialized()
{
    if (!namesInitialized)
    {
        MemberInfo[] enumMembers = typeof(TEnum).GetMembers(
                BindingFlags.Public
                | BindingFlags.Static
                | BindingFlags.GetField);

        foreach (FieldInfo enumMember in enumMembers)
        {
            TEnum enumValue =
                enumMember.GetValue(null) as TEnum;

            if (enumValue != null)
                enumValue.Name = enumMember.Name;
        }
        namesInitialized = true;
    }
}</pre>
<li>And finally I added this line at the end or the register method, just before the “return instance” statement :
<pre class="brush: csharp; gutter: false; toolbar: false;">namesInitialized = false;</pre>
</li>
</ol>
<p>This mechanism ensures that the enum names are all computed using reflection. It assigns each enum value the name of the public static member to which it has been assigned (given the member has already been assigned and is of the correct type).</p>
<h3>Serializing and deserializing</h3>
<p><img style="display: block; float: none; margin-left: auto; margin-right: auto" src="http://www.pirrmann.net/wp-content/uploads/2012/09/step-5.png"></p>
<p>Nice ! We’ve made progress, really. Now we want to be able to serialize and deserialize the values from and to strings, as well as from the underlying primitive type.</p>
<p>Serializing to a string has been implemented from the start by the ToString() method. Deserializing will imply 4 methods signatures :</p>
<ul>
<li>bool TryParse(string value, out TEnum result)
<li>bool TryParse(string value, bool ignoreCase, out TEnum result)
<li>TEnum Parse(string value)
<li>TEnum Parse(string value, bool ignoreCase) </li>
</ul>
<p>In the end the implementation is the following :</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">public static bool TryParse(string value,
                            bool ignoreCase,
                            out TEnum result)
{
    TEnum[] instances = registeredInstances
        .Values
        .Where(
            e =&gt; e.Name.Equals(
                value,
                ignoreCase
                    ? StringComparison.InvariantCultureIgnoreCase
                    : StringComparison.InvariantCulture))
        .ToArray();

    if (instances.Length == 1)
    {
        result = instances[0];
        return true;
    }
    else
    {
        result = default(TEnum);
        return false;
    }
}</pre>
<p>The 3 other signatures simply rely on the previous method.</p>
<p>Concerning the other type of conversion (i.e. from and to the underlying primitive type), to stay as close as possible as how classical enums work, I have defined the following operator :</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">public static implicit operator T(PolymorphicEnum&lt;T, TEnum&gt; x)
{
    return x.Ordinal;
}</pre>
<p>And the second one :</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">public static explicit operator PolymorphicEnum&lt;T, TEnum&gt;(T x)
{
    TEnum enumInstance;
    if (!registeredInstances.TryGetValue(x, out enumInstance))
        throw new ArgumentException(
            string.Format("Enum value {0} not found", x, "x"));

    return enumInstance;
}</pre>
<h3>Embedding data</h3>
<p><img style="display: block; float: none; margin-left: auto; margin-right: auto" src="http://www.pirrmann.net/wp-content/uploads/2012/09/step-6.png"></p>
<p>Now we’re going to add an extra requirement : we want to embed data in the enum values. In order to store this values, I’ll be as open as I can and add an extra property typed as “object” :</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">protected object Data { get; private set; }</pre>
<p>I’ll also add an extra optional parameter in the two Register methods, that become :</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">protected static TEnum Register(
    Nullable&lt;T&gt; ordinal = null,
    object data = null)
{
    return Register&lt;TEnum&gt;(ordinal, data);
}</pre>
<p>and :</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">protected static TEnum Register&lt;TEnumInstance&gt;(
    Nullable&lt;T&gt; ordinal = null,
    object data = null)
where TEnumInstance : TEnum, new()
{
    if (!ordinal.HasValue)
    {
        ordinal = registeredInstances.Any()
            ? registeredInstances.Keys.Max().PlusOne()
            : default(T);
    }

    TEnum instance = new TEnumInstance();
    instance.Ordinal = ordinal.Value;
    instance.Data = data;

    registeredInstances.Add(ordinal.Value, instance);

    namesInitialized = false;

    return instance;
}</pre>
<p>As you can see, not much as changed, but that is all there is to do ! A single point to mention is that nothing prevents the derived classes to change the state of the objects stored in the “Data” property. So when writing these derived classes, the developer has to be careful to enforce immutability.</p>
<h3>Enforcing consistency</h3>
<p><img style="display: block; float: none; margin-left: auto; margin-right: auto" src="http://www.pirrmann.net/wp-content/uploads/2012/09/step-7.png"></p>
<p>OK, I’ll soon stop this never-ending post, but there is a last detail that I wanted to explain, that is how I take care that once the set of values of an enum has been defined, it cannot be extended from any other class.</p>
<p>In order to register new values, you have to add new enum instances in the registeredInstances member. The way to do this is to call one of the two overloads or the Register method. If you wanted to bypass these methods, you would need to have access to the registeredInstances member, which is private in the base class, so that settles this point. But what prevents you from calling the Register methods in weird situations ? Let’s take a look at the following inheritance :</p>
<p align="center"><img src="http://www.pirrmann.net/wp-content/uploads/2012/09/enforce-consistency-classes.png"></p>
<p>Put in code, it becomes :</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">public class SomeEnum : PolymorphicEnum&lt;SomeEnum&gt;
{
    public static SomeEnum FirstValue = Register();
    public static SomeEnum SecondValue = Register();
}

public class OtherEnum : PolymorphicEnum&lt;SomeEnum&gt;
{
    public static SomeEnum ThirdValueAttempt = Register();
}

public class OtherChildEnum : SomeEnum
{
    public static SomeEnum FourthValueAttempt = Register();
}</pre>
<p>The above code is valid, and compiles without any warning. The register method is a protected method, so it can be called :</p>
<ul>
<li>from any class deriving from the same base classe PolymorphicEnum&lt;T&gt; (with the same T type), for instance here the OtherEnum class,
<li>from any sub-class, for instance here the OtherChildEnum class. </li>
</ul>
<p>To prevent the registration of invalid values, we check at the very beginning of the Register method that the type which called the method is the same as the type being registered. To do so, we take a look at the call stack, either at the first or the second stack frame, depending on the overload of Register that was called :</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">StackFrame frame = new StackFrame(1);
if (frame.GetMethod().Name == "Register")
    frame = new StackFrame(2);

MethodBase enumConstructor = frame.GetMethod();
if (enumConstructor.DeclaringType != typeof(TEnum))
    throw new EnumInitializationException(
        "Enum members cannot be registered from other enums.");
</pre>
<p>This prevents the user code from registering undesired values. But there is still an edge case to be handled, pointed to me be @cyriux…</p>
<p>Let me show you what’s wrong… Remember the very first sample about the gestures ? Don’t look back ! Here is the code again :</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">/** PolymorphicEnum have behavior! **/
public class Gesture : PolymorphicEnum&lt;Gesture&gt;
{
    public static Gesture ROCK = Register&lt;RockGesture&gt;();
    public static Gesture PAPER = Register();
    public static Gesture SCISSORS = Register();

    // we can implement with the integer representation
    public virtual bool Beats(Gesture other)
    {
        return this.Ordinal - other.Ordinal == 1;
    }

    private class RockGesture : Gesture
    {
        public override bool Beats(Gesture other)
        {
            return other == SCISSORS;
        }
    }
}</pre>
<p>The problem with this implementation is maybe not that obvious, but what if I write the following code ?</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">public class Godzilla : Gesture
{
    public static Godzilla Instance = new Godzilla();

    public override bool Beats(Gesture other)
    {
        return true;
    }
}</pre>
<p>Yes, this is valid code. And the following test is green !</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">[TestMethod]
public void godzilla_beats_all()
{
    Assert.IsTrue(Godzilla.Instance.Beats(Gesture.ROCK));
    Assert.IsTrue(Godzilla.Instance.Beats(Gesture.PAPER));
    Assert.IsTrue(Godzilla.Instance.Beats(Gesture.SCISSORS));
}</pre>
<p>Now imagine if the Gesture enum was part of a library… Nothing would prevent user code from providing a Godzilla instance wherever a Gesture is asked…</p>
<p>There are several ways to secure this implementation :</p>
<ol>
<li>The logic could be provided as embedded data in the registration or the enum (using a lambda expression). Although this is the solution I would prefer (“composition over inheritance”, see the <a href="http://notonlyoo.org/" target="_blank">Manifesto for Not Only Object-Oriented Development</a>), this would not be a real polymorphic behaviour anymore !
<li>If we want to solve this using polymorphism, this is what I came up with. I added the following two “Checked” methods and the IsRegistered property in the base class : </li>
</ol>
<pre class="brush: csharp; gutter: false; toolbar: false;">private bool IsRegistered
{
    get { return registeredInstances.Values.Contains(this); }
}

protected TEnum Checked(TEnum value)
{
    if (!value.IsRegistered)
        throw new UnregisteredEnumException(
            "This enum is not registered");

    return value;
}

protected void Checked(Action a)
{
    if (!IsRegistered)
        throw new UnregisteredEnumException(
            "This enum is not registered");

    a.Invoke();
}

protected TReturn Checked&lt;TReturn&gt;(Func&lt;TReturn&gt; f)
{
    if (!IsRegistered)
        throw new UnregisteredEnumException(
            "This enum is not registered");

    return f.Invoke();
}</pre>
<p>Using these new methods, here is how we could rewrite the previous “Godzilla” sample :</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">public class CheckedGesture : PolymorphicEnum&lt;CheckedGesture&gt;
{
    public static CheckedGesture ROCK = Register&lt;RockGesture&gt;();
    public static CheckedGesture PAPER = Register();
    public static CheckedGesture SCISSORS = Register();

    // we can implement with the integer representation
    public bool Beats(CheckedGesture other)
    {
        return Checked(() =&gt; this.BeatsImpl(Checked(other)));
    }

    protected virtual bool BeatsImpl(CheckedGesture other)
    {
        return this.Ordinal - other.Ordinal == 1;
    }

    private class RockGesture : CheckedGesture
    {
        protected override bool BeatsImpl(CheckedGesture other)
        {
            return other == SCISSORS;
        }
    }
}</pre>
<p>And the method that can be overridden in the new Godzilla class in now the BeatsImpl one :</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">public class CagedGodzilla : CheckedGesture
{
    public static CagedGodzilla Instance = new CagedGodzilla();

    protected override bool BeatsImpl(CheckedGesture other)
    {
        return true;
    }
}</pre>
<p>This now works correctly and the CagedGodzilla can’t be used in place of a CheckedGesture without throwing an UnregisteredEnumException. But this seems a little bit over-engineered, isn’t it ?</p>
<p>All of this horrible mess is <a href="https://github.com/pirrmann/PolymorphicEnum" target="_blank">available on my GitHub</a>, along with the unit tests and the different steps of the implementation, which I’ve described in this post.</p>
<img src="http://feeds.feedburner.com/~r/pirrmann/~4/EjiqRghbwyk" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.pirrmann.net/polymorphic-enums-in-c-sharp-implementation-revealed/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.pirrmann.net/polymorphic-enums-in-c-sharp-implementation-revealed/</feedburner:origLink></item>
		<item>
		<title>Polymorphic enums in C#, generic incrementation</title>
		<link>http://feedproxy.google.com/~r/pirrmann/~3/zXiZvk7WXdw/</link>
		<comments>http://www.pirrmann.net/polymorphic-enums-in-c-sharp-generic-incrementation/#comments</comments>
		<pubDate>Tue, 18 Sep 2012 04:46:13 +0000</pubDate>
		<dc:creator>Pierre IRRMANN</dc:creator>
				<category><![CDATA[Syntax Puzzles]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Enum]]></category>
		<category><![CDATA[Puzzle]]></category>

		<guid isPermaLink="false">http://www.pirrmann.net/?p=154</guid>
		<description><![CDATA[During the implementation of my polymorphic enum, I have chosen to allow several types for the underlying “ordinal” value, as it is also possible for standard C# enums… From the MSDN documentation, the allowed underlying types for enum types are &#8230; <a href="http://www.pirrmann.net/polymorphic-enums-in-c-sharp-generic-incrementation/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p align="justify"><img style="display: inline; float: right" align="right" src="http://www.pirrmann.net/wp-content/uploads/2012/09/x-plus-one.png" width="270" height="87">During the implementation of my polymorphic enum, I have chosen to allow several types for the underlying “ordinal” value, as it is also possible for standard C# enums…</p>
<p align="justify">From the <a href="http://msdn.microsoft.com/en-us/library/exx3b86w.aspx" target="_blank">MSDN documentation</a>, the allowed underlying types for enum types are the following (although other value types such as char are eligible, their use is not recommended) :</p>
<table>
<tbody>
<tr>
<th>
<p>Type</p>
</th>
<th>
<p>Size</p>
</th>
</tr>
<tr>
<td>
<p><a href="http://msdn.microsoft.com/en-us/library/d86he86x.aspx">sbyte</a></p>
</td>
<td>
<p>Signed 8-bit integer</p>
</td>
</tr>
<tr>
<td>
<p><a href="http://msdn.microsoft.com/en-us/library/5bdb6693.aspx">byte</a></p>
</td>
<td>
<p>Unsigned 8-bit integer</p>
</td>
</tr>
<tr>
<td>
<p><a href="http://msdn.microsoft.com/en-us/library/ybs77ex4.aspx">short</a></p>
</td>
<td>
<p>Signed 16-bit integer</p>
</td>
</tr>
<tr>
<td>
<p><a href="http://msdn.microsoft.com/en-us/library/cbf1574z.aspx">ushort</a></p>
</td>
<td>
<p>Unsigned 16-bit integer</p>
</td>
</tr>
<tr>
<td>
<p><a href="http://msdn.microsoft.com/en-us/library/5kzh1b5w.aspx">int</a></p>
</td>
<td>
<p>Signed 32-bit integer</p>
</td>
</tr>
<tr>
<td>
<p><a href="http://msdn.microsoft.com/en-us/library/x0sksh43.aspx">uint</a></p>
</td>
<td>
<p>Unsigned 32-bit integer</p>
</td>
</tr>
<tr>
<td>
<p><a href="http://msdn.microsoft.com/en-us/library/ctetwysk.aspx">long</a></p>
</td>
<td>
<p>Signed 64-bit integer</p>
</td>
</tr>
<tr>
<td>
<p><a href="http://msdn.microsoft.com/en-us/library/t98873t4.aspx">ulong</a></p>
</td>
<td>
<p>Unsigned 64-bit integer</p>
</td>
</tr>
</tbody>
</table>
<p align="justify">In order to enable the ordinal parameter to be optional in the registration of enum values, I had to find a way to compute an automatic value. The rule I wanted to apply was very simple : if there is no value already register, use zero, else use the maximum value already registered, plus one. But how do you write such code without checking the type in an ugly fashion ?</p>
<p align="justify">Generic constraints are somehow limited : I can force the ordinal type to be a value type by using a “where T : struct” constraints, but there is no such thing as a “IPrimitiveNumericValue” interface !</p>
<p>Here is where I got to, using generics and lambdas…</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">public static class Incrementer
{
    private static Func&lt;T, T&gt; GetFunc&lt;T&gt;(Func&lt;T, T&gt; f)
    {
        return f;
    }
    [...]</pre>
<p align="justify">I first define static class and a private static helper function that take a Func&lt;T, T&gt; and returns… the unmodified argument. This is just a hint for the compiler, because I’m going to use lambdas and as you might know, a lambda can either be converted to a delegate (code) or to an expression tree representing the lambda (data). Without any indication, the compiler can’t infer the expected type, so we have to help him…</p>
<p>Then, the class defines a static field and initialises it in its static constructor :</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">private static Dictionary&lt;Type, object&gt; incrementers;

static Incrementer()
{
    incrementers = new Dictionary&lt;Type, object&gt;();
    incrementers.Add(typeof(sbyte), GetFunc&lt;sbyte&gt;(i =&gt; (sbyte)(i + 1)));
    incrementers.Add(typeof(byte), GetFunc&lt;byte&gt;(i =&gt; (byte)(i + 1)));
    incrementers.Add(typeof(short), GetFunc&lt;short&gt;(i =&gt; (short)(i + 1)));
    incrementers.Add(typeof(ushort), GetFunc&lt;ushort&gt;(i =&gt; (ushort)(i + 1)));
    incrementers.Add(typeof(int), GetFunc&lt;int&gt;(i =&gt; i + 1));
    incrementers.Add(typeof(uint), GetFunc&lt;uint&gt;(i =&gt; i + 1));
    incrementers.Add(typeof(long), GetFunc&lt;long&gt;(i =&gt; i + 1));
    incrementers.Add(typeof(ulong), GetFunc&lt;ulong&gt;(i =&gt; i + 1));
}</pre>
<p align="justify">At this point, all the required incrementing functions are expressed as lambdas and registered in a dictionary.</p>
<p>The only method left to write is the PlusOne method :</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">public static T PlusOne&lt;T&gt;(this T value)
    where T : struct
{
    object incrementer;
    if (!incrementers.TryGetValue(typeof(T), out incrementer))
        throw new NotSupportedException(
            "This type is not supported.");

    return ((Func&lt;T, T&gt;)incrementer).Invoke(value);
}</pre>
<p>Type checking and dictionary lookup. That’s it !</p>
<img src="http://feeds.feedburner.com/~r/pirrmann/~4/zXiZvk7WXdw" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.pirrmann.net/polymorphic-enums-in-c-sharp-generic-incrementation/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.pirrmann.net/polymorphic-enums-in-c-sharp-generic-incrementation/</feedburner:origLink></item>
		<item>
		<title>Polymorphic enums in C# ?</title>
		<link>http://feedproxy.google.com/~r/pirrmann/~3/0ssIyi3clfI/</link>
		<comments>http://www.pirrmann.net/polymorphic-enums-in-c-sharp/#comments</comments>
		<pubDate>Mon, 17 Sep 2012 04:25:40 +0000</pubDate>
		<dc:creator>Pierre IRRMANN</dc:creator>
				<category><![CDATA[Syntax Puzzles]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Enum]]></category>
		<category><![CDATA[Polymorphism]]></category>
		<category><![CDATA[Puzzle]]></category>

		<guid isPermaLink="false">http://www.pirrmann.net/?p=149</guid>
		<description><![CDATA[Using Java as a inspiration source for C# (hmm wait, hasn’t that already been done from the start ?) A few weeks ago, I read this post by @cyriux, describing how you could use polymorphic enums in Java. Actually, I &#8230; <a href="http://www.pirrmann.net/polymorphic-enums-in-c-sharp/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<h3>Using Java as a inspiration source for C# (<em>hmm wait, hasn’t that already been done from the start ?</em>)</h3>
<p><img style="margin: 0px 0px 0px 20px; display: inline; float: right" align="right" src="http://www.pirrmann.net/wp-content/uploads/2012/09/gestures.jpg"></p>
<p align="justify">A few weeks ago, I read <a href="http://cyrille.martraire.com/2012/08/java-enums-you-have-grace-elegance-and-power-and-this-is-what-i-love/" target="_blank">this post by @cyriux</a>, describing how you could use polymorphic enums in Java. Actually, I had already heard him telling that enums in C# were nothing like the ones in Java. And even if he’s sometimes trolling, he’s really got a point there. Then I thought to myself : I know I won’t be able to add this syntax to C#, because I can’t change the compiler, but how clause could I get to polymorphic enums ? Let’s try that…</p>
<p>First, what <strong>are</strong> the common characteristics of an enum ?</p>
<ul>
<li>enums bind together a scalar value and a string representation, so enums can be converted to and parsed from strings
<li>for the same reason, enums can be casted to and from scalar values (int, long, short…),
<li>enums should be immutable (in fact, unless you introduce some mutable state in them, they already are),
<li>enums cannot be extended by other types : once defined, their set of values is closed and cannot be modified. </li>
</ul>
<p>I haven’t checked for Java, but here are some other characteristics of C# enums :</p>
<ul>
<li>enums are a value types,
<li>enums implement the following interfaces : <a href="http://msdn.microsoft.com/fr-fr/library/vstudio/system.icomparable.aspx" target="_blank">IComparable</a>, <a href="http://msdn.microsoft.com/fr-fr/library/vstudio/system.iformattable.aspx" target="_blank">IFormattable</a>, <a href="http://msdn.microsoft.com/en-us/library/system.iconvertible.aspx" target="_blank">IConvertible</a> </li>
</ul>
<p>In order to build a type that behaves like an enum, I’ve made the following decisions :</p>
<ul>
<li>I want to build a base type from which actual enums will derive. As there is nothing in C# as an abstract struct (value type), I have to implement a class and not a struct.
<li>In order to obtain a value type behaviour (value comparison instead of instance equality), I’ll will have to implement it.
<li>I will implement interfaces <a href="http://msdn.microsoft.com/fr-fr/library/vstudio/system.icomparable.aspx" target="_blank">IComparable</a> and <a href="http://msdn.microsoft.com/en-us/library/system.iconvertible.aspx" target="_blank">IConvertible</a>, but I haven’t really seen any use case where I would use <a href="http://msdn.microsoft.com/fr-fr/library/vstudio/system.iformattable.aspx" target="_blank">IFormattable</a>, so I chose not to implement it.
<li>Enums in C# don’t have an Ordinal property, but I’ll introduce one, so that I can write unit tests as close as possible as @cyriux’s ones. It will look a little bit Java-ish… but of course I’ll keep the C# casing convention.
<li>The underlying type used to represent an enum is an integer by default, but other types can be used, such as a long or an unsigned short. I will try to make the enums definitions as short a possible, so I’ll use generics and take advantage of the type inference system. </li>
</ul>
<h3>My C# enum has behaviour</h3>
<p>Enough text there ! Directly inspired from @cyriux’s post’s first sample “<a href="http://en.wikipedia.org/wiki/Rock-paper-scissors" target="_blank">Rock &#8211; paper &#8211; scissors</a>”, here is the test cases that I want to execute :</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">[TestMethod]
public void paper_beats_rock()
{
    Assert.IsTrue(Gesture.PAPER.Beats(Gesture.ROCK));
    Assert.IsFalse(Gesture.ROCK.Beats(Gesture.PAPER));
}

[TestMethod]
public void scissors_beats_paper()
{
    Assert.IsTrue(Gesture.SCISSORS.Beats(Gesture.PAPER));
    Assert.IsFalse(Gesture.PAPER.Beats(Gesture.SCISSORS));
}

[TestMethod]
public void rock_beats_scissors()
{
    Assert.IsTrue(Gesture.ROCK.Beats(Gesture.SCISSORS));
    Assert.IsFalse(Gesture.SCISSORS.Beats(Gesture.ROCK));
}</pre>
<p>And here is the implementation of the enum, built upon my PolymorphicEnum class :</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">/** PolymorphicEnum have behavior! **/
public class Gesture : PolymorphicEnum&lt;Gesture&gt;
{
    public static Gesture ROCK = Register&lt;RockGesture&gt;();
    public static Gesture PAPER = Register();
    public static Gesture SCISSORS = Register();

    // we can implement with the integer representation
    public virtual bool Beats(Gesture other)
    {
        return this.Ordinal - other.Ordinal == 1;
    }

    private class RockGesture : Gesture
    {
        public override bool Beats(Gesture other)
        {
            return other == SCISSORS;
        }
    }
}</pre>
<p>As you can see in the implementation, it is now possible to define a Gesture enum, that exposes 3 static properties of type Gesture. One of these properties, ROCK, is in fact an instance of RockGesture, which is a Gesture that overrides the behaviour of Beats method.</p>
<h3>Strategy Pattern</h3>
<p>All the Java sample from the post can now be ported to C# ! The next one was the Eurovision contest, where an abstract method was defined in the base enum, and overridden in each enum instance, in order to implement a strategy pattern. This is where I admit I couldn’t get the same behaviour, as for internal implementations reasons I needed my base class to not be abstract… So I had to define a default behaviour :</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">public class EurovisionNotification
    : PolymorphicEnum&lt;EurovisionNotification&gt;
{
    /** Default behavior : I don't want to know ! */
    public virtual bool MustNotify(String eventCity,
                                   String userCity)
    {
        return false;
    }

    /** I love Eurovision, don't want to miss it, never! */
    private class EurovisionNotificationAlways
        : EurovisionNotification
    {
        public override bool MustNotify(string eventCity,
                                        string userCity)
        {
             return true;
        }
    }

    /**
     * I only want to know about Eurovision if it takes place
     * in my city, so that I can take holidays elsewhere at
     * the same time
     */
    private class EurovisionNotificationOnlyCity
        : EurovisionNotification
    {
        public override bool MustNotify(string eventCity,
                                        string userCity)
        {
             return eventCity.Equals(
                userCity,
                StringComparison.InvariantCultureIgnoreCase);
        }
    }

    public static EurovisionNotification ALWAYS =
        Register&lt;EurovisionNotificationAlways&gt;();
    public static EurovisionNotification ONLY_IN_MY_CITY =
        Register&lt;EurovisionNotificationOnlyCity&gt;();
    public static EurovisionNotification NEVER =
        Register();
}</pre>
<h3>State Pattern</h3>
<p>The next sample is the one where a baby is represented as a state machine :</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">public class BabyState : PolymorphicEnum&lt;BabyState&gt;
{
    public static BabyState POOP = Register();

    public static BabyState SLEEP =
        Register(data: new { Next = POOP });

    public static BabyState EAT =
        Register(data: new { Next = SLEEP });

    public static BabyState CRY =
        Register(data: new { Next = EAT });

    public BabyState Next(bool discomfort)
    {
        if (discomfort)
            return CRY;

        return this.Data == null
            ? EAT
            : (BabyState)((dynamic)this.Data).Next;
    }
}</pre>
<p><img style="display: inline; float: right" align="right" src="http://www.pirrmann.net/wp-content/uploads/2012/09/baby-states.png"></p>
<p>Just as for the Java enums, “we can reference enum constants between them, with the restriction that only constants defined before can be referenced”. The workaround here, as @cyriux wrote in his post, is to open the cycle. This builds allows us to build the graph on the right.</p>
<p>We can notice here that in order to embed data in an enum value, I have introduced an extra parameter “data” in the Enum method, which is responsible for the Enum values registration. Using this extra parameter, we can go back to the Eurovision sample and rewrite this way :</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">using Policy = System.Func&lt;string, string, bool&gt;;

public class EurovisionNotificationLambda
    : PolymorphicEnum&lt;EurovisionNotificationLambda&gt;
{
    private static Policy Policy(Policy f) { return f; }

    public static EurovisionNotificationLambda ALWAYS =
        Register(data: Policy((eventCity, userCity) =&gt; true));

    public static EurovisionNotificationLambda ONLY_IN_MY_CITY =
        Register(data: Policy((eventCity, userCity) =&gt;
            eventCity.Equals(
                userCity,
                StringComparison.InvariantCultureIgnoreCase)));

    public static EurovisionNotificationLambda NEVER =
        Register(data: Policy((eventCity, userCity) =&gt; false));

    public bool MustNotify(String eventCity, String userCity)
    {
        return ((Policy)this.Data).Invoke(eventCity, userCity);
    }
}</pre>
<p>In this implementation, each enum value owns its notification policy, in the form of a types delegate, which is declared using a lambda expression.</p>
<h3>Enum-non-optimized collections</h3>
<p>Ok, I haven’t gone so far as implementing optimized collections that take advantage of the integer nature of enums ! So not all the arguments listed by @cyriux apply to my C# implementation… But I still get polymorphism, the correct Equals, GetHashCode, ToString, string or integer serialization, and singleton-ness for free, with very little code ! Feel free to experiment with it if you want, the whole project will be available on my GitHub very soon.</p>
<p>In a next post, I’m going to talk about some points of interest in my PolymorphicEnum implementation.</p>
<img src="http://feeds.feedburner.com/~r/pirrmann/~4/0ssIyi3clfI" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.pirrmann.net/polymorphic-enums-in-c-sharp/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.pirrmann.net/polymorphic-enums-in-c-sharp/</feedburner:origLink></item>
		<item>
		<title>Using BDD and SpecFlow to write readable tests</title>
		<link>http://feedproxy.google.com/~r/pirrmann/~3/Wb47wtmUHo4/</link>
		<comments>http://www.pirrmann.net/using-bdd-and-specflow-to-write-readable-tests/#comments</comments>
		<pubDate>Fri, 31 Aug 2012 12:04:09 +0000</pubDate>
		<dc:creator>Pierre IRRMANN</dc:creator>
				<category><![CDATA[LINQ]]></category>
		<category><![CDATA[AST]]></category>
		<category><![CDATA[BDD]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[LINQ Provider]]></category>
		<category><![CDATA[SpecFlow]]></category>

		<guid isPermaLink="false">http://www.pirrmann.net/?p=142</guid>
		<description><![CDATA[In this post, I&#8217;m going to use SpecFlow and the Gherkin syntax to write tests in a natural language. I want to show how easy that is to setup, when you have code that is already testable, and how it &#8230; <a href="http://www.pirrmann.net/using-bdd-and-specflow-to-write-readable-tests/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>In this post, I&#8217;m going to use <a href="http://specflow.org/" target="_blank">SpecFlow</a> and <a href="https://github.com/cucumber/cucumber/wiki/Gherkin" target="_blank">the Gherkin syntax</a> to write tests in a natural language. I want to show how easy that is to setup, when you have code that is already testable, and how it helps you to write better tests in a few minutes.</p>
<p><img style="margin: 0px 10px 0px 0px; display: inline; float: left" align="left" src="http://www.pirrmann.net/wp-content/uploads/2012/08/specflow-logo.png">SpecFlow is a testing component / framework / Visual Studio plug-in, which allows you to write your tests in a natural fashion, and run these tests using your favourite test-runner. As quoted from their web site :</p>
<blockquote><p>SpecFlow aims at bridging the communication gap between domain experts and developers by binding business readable behavior specifications to the underlying implementation. Our mission is to provide a pragmatic and frictionless approach to Acceptance Test Driven Development and Behavior Driven Development for .NET projects today.</p>
</blockquote>
<p>SpecFlow is build upon <a href="https://github.com/cucumber/cucumber/wiki/Gherkin" target="_blank">the Gherkin syntax</a>, which is a grammar that has been designed to write behaviour specifications. This syntax first emerged in the Ruby community, and is linked to a project called Cucumber. For more details, you can check out <a href="http://cukes.info">http://cukes.info</a> :</p>
<blockquote><p>Cucumber is Aslak Hellesøy’s rewrite of RSpec’s “Story runner”, which was originally written by Dan North. (Which again was a rewrite of his first implementation &#8211; RBehave. RBehave was his Ruby port of JBehave)…</p>
</blockquote>
<p><img style="margin: 0px 0px 10px 10px; display: inline; float: right" align="right" src="http://www.pirrmann.net/wp-content/uploads/2012/08/cuke-logo.png" width="370" height="71">Gherkin is Cucumber’s DSL (<a href="http://en.wikipedia.org/wiki/Domain-specific_language" target="_blank">Domain Specific Language</a>) and as such, is not linked to a particular language or technology. It can therefore be used in .NET by using SpecFlow. It has very few keywords, yet is very powerful. The best way to explain how it works is to show an example of a test scenario :</p>
<pre>Scenario: Filter on age
    Given I have written a query against the provider
    And I have added a Age &gt;= 36 where clause
    Given The people finder service filters on Age &gt;= 36
    When I execute the query
    Then The service parameter should be Age IsGreaterThan 36
    And The result count should be 3
    And The result should validate the servicePredicate</pre>
<p>From now on, you might have noticed that I’m working on my Linq provider again… but in this post I’ll talk only about testing and using SpecFlow, so don’t run away, even if you’re sick of expression trees !</p>
<p>What SpecFlow allows you to do, is to write your specifications and tests cases in plain text, and generate tests classes from it. It has several nice features that help you organize your tests and examples, which I’ll describe soon.</p>
<p><img style="display: inline; float: right" align="right" src="http://www.pirrmann.net/wp-content/uploads/2012/08/nuget-logo.png"><img style="margin: 0px 10px 0px 0px; display: inline; float: left" align="left" src="http://www.pirrmann.net/wp-content/uploads/2012/08/vsix-logo.png" width="64" height="64">In order to use SpecFlow in your project, the easiest way is to add a reference to it in your test project, using the NuGet package manager. To get Visual Studio integration, you should also install the “SpecFlow integration for Visual Studio extension”.</p>
<p>When doing BDD, the tests are written in order to tests features. For each feature of an application (or component, or class), you can create a feature file. As you can see from the previous example, tests will be organised around the concept of “scenario”. Each feature file can contain several scenarios. The binding between a scenario and the actual tests implementation will be done on a line-by-line basis. Each line of the scenario will end up as a method call :</p>
<ul>
<li>the “Given” and associated “And” clauses will correspond to methods that set up the tests,
<li>the “When” clause will trigger some action or event that drives the behaviour that is aimed to be tested,
<li>the “Then” and associated “And” clauses will perform the assertions that determine the outcome of the test.</li>
</ul>
<p>In order to do the matching between lines in the scenario and methods in the test class, the methods are marked with the appropriate SpecFlow attributes, that take the model of the expected sentence as an argument. This model can include groups of capturing expressions, that are used to populate the method parameters at run time.</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">[Given(@"I have added a (.*) where clause")]
public void GivenIHaveAddedAWhereClause(string predicate)</pre>
<p>If we go back to the test scenario shown earlier, the best way to see how the test is executed is to look at the generated test output:</p>
<pre>Given I have written a query against the provider
-&gt; done: FeaturesTest.GivenIHaveWrittenAQuery() (0,0s)
And I have added a Age &gt;= 36 where clause
-&gt; done: FeaturesTest.GivenIHaveAddedAWhereClause("Age &gt;= 36") (0,0s)
Given The people finder service filters on Age &gt;= 36
-&gt; done: FeaturesTest.GivenThePeopleFinderServiceFiltersOn("Age &gt;= 36") (0,0s)
When I execute the query
-&gt; done: FeaturesTest.WhenIExecuteTheQuery() (0,1s)
Then The service parameter should be Age IsGreaterThan 36
-&gt; done: FeaturesTest.ThenTheServiceParameter("Age IsGreaterThan 36") (0,0s)
And The result count should be 3
-&gt; done: FeaturesTest.ThenTheResultCount(3) (0,0s)
And The result should validate the servicePredicate
-&gt; done: FeaturesTest.ThenTheResultShouldValidatetheServicePredicate() (0,0s)
</pre>
<p>We can see that each line of the scenario is used to call a method. In order to “accumulate” the conditions and perform the assertions on the results, we use a class that defines the test context :</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">public class ServiceContext
{
    // Data context
    public IEnumerable&lt;Person&gt; AllPeople { get; set; }

    // Input
    public List&lt;string&gt; Query { get; set; }
    public List&lt;string&gt; ServiceLambdas { get; set; }

    // Service predicate, built upon the ServiceLambdas
    public Expression&lt;Func&lt;Person, bool&gt;&gt;
                            ServicePredicate {get; set;}

    // Output
    public List&lt;Person&gt; Results { get; set; }
    public SearchCriteria PassedCriteria { get; set; }
}</pre>
<p>Using this context class, the methods corresponding to the “Given” populate the properties used as the test input, the “When” performs the action, which populates the output based on the input, and the “Then” make assertions on the output.</p>
<p>The next step is to add additional test cases. A simple way could be to simply copy-paste the previous scenario, and change the parameters. But as we always want to void duplication, we’ll use a very handful feature here and use a “Scenario Outline” and examples :</p>
<pre class="brush: plain; gutter: false; toolbar: false;">Scenario Outline: Filter on a single criterion
    Given I have written a query against the provider
    And I have added a &lt;predicate&gt; where clause
    Given The people finder service filters on &lt;servicePredicate&gt;
    When I execute the query
    Then The service parameter should be &lt;serviceParameter&gt;
    And The result count should be &lt;resultsCount&gt;
    And The result should validate the servicePredicate
    Examples: 
    | predicate                     | servicePredicate              | serviceParameter            | resultsCount |
    | Age &gt;= 36                     | Age &gt;= 36                     | Age IsGreaterThan 36        | 3            |
    | Age &gt;= 36                     |                               | Age IsGreaterThan 36        | 6            |
    | FirstName.StartsWith("Scar")  | FirstName.StartsWith("Scar")  | FirstName StartsWith Scar   | 1            |
    | LastName == Alba              |                               | LastName Equals Alba        | 6            |</pre>
<p>The main advantage of this syntax is that it is self-explanatory ! Once the scenario outline is prepared, we list all the cases that we want to test.</p>
<p>If you’ve read the post carefully up to this point, you might have noticed that my scenario makes assertions on the number of results, but that there is nothing that sets-up the test data. In fact, there is a hidden “Given” clause that is used across the whole feature file. The way to to this is by using the keyword “Background”:</p>
<pre class="brush: plain; gutter: false; toolbar: false;">Background: 
    Given The people are
    | FirstName | LastName    | Age | Id                                     |
    | Scarlett  | Johansson   | 27  | {8c319634-935d-4681-adcc-02d5347fe6c4} |
    | Jessica   | Alba        | 31  | {32a84597-8c3d-44bc-a1a5-6538188e9d25} |
    | Penelope  | Cruz        | 38  | {5aa0eb59-3961-472f-b829-7d54ac8eeeef} |
    | Reese     | Witherspoon | 36  | {77fcd741-3839-4692-925f-a3a0eb19cf42} |
    | Charlize  | Theron      | 36  | {e37290f6-d376-44e2-944d-d0af13c1a75c} |
    | Mouloud   | Achour      | 31  | {18af541a-a5dc-41d2-af47-479b1c06e216} |
</pre>
<p>One last thing : although parsing the lambda given as arguments in the scenario is a topic of its own and could be discussed further, setting up the test data from the previous “Given” clause is delightfully easy, and I couldn’t help not showing you the code :</p>
<pre class="brush: plain; gutter: false; toolbar: false;">[Given(@"The people are")]
public void GivenThePeopleAre(Table people)
{
    this.context.AllPeople = people.CreateSet&lt;Person&gt;();
}</pre>
<p>As a conclusion, I strongly recommend to give SpecFlow a try, you won’t regret it !</p>
<p>All the source code from this post and the Linq Provider Series is now available on my Github at <a title="https://github.com/pirrmann/LinqToService" href="https://github.com/pirrmann/LinqToService" target="_blank">https://github.com/pirrmann/LinqToService</a>. Please feel free to fork and/or contribute, and I’d also be really happy to get feedback !</p>
<img src="http://feeds.feedburner.com/~r/pirrmann/~4/Wb47wtmUHo4" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.pirrmann.net/using-bdd-and-specflow-to-write-readable-tests/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.pirrmann.net/using-bdd-and-specflow-to-write-readable-tests/</feedburner:origLink></item>
		<item>
		<title>Linq provider : an attempt… part 6</title>
		<link>http://feedproxy.google.com/~r/pirrmann/~3/1tTLOKObiQE/</link>
		<comments>http://www.pirrmann.net/linq-provider-an-attempt-part-6/#comments</comments>
		<pubDate>Thu, 05 Jul 2012 20:04:51 +0000</pubDate>
		<dc:creator>Pierre IRRMANN</dc:creator>
				<category><![CDATA[LINQ]]></category>
		<category><![CDATA[AST]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[LINQ Provider]]></category>

		<guid isPermaLink="false">http://www.pirrmann.net/?p=134</guid>
		<description><![CDATA[Jammin’ Jammin’ Just a month ago, I’ve had the opportunity to get feedback from @cyriux and Jérôme during the monthly @ArollaFr’s Code Jam, and we made important changes in the code. The concept of a Code Jam is simple : &#8230; <a href="http://www.pirrmann.net/linq-provider-an-attempt-part-6/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<h3>Jammin’ Jammin’</h3>
<p>Just a month ago, I’ve had the opportunity to get feedback from @cyriux and Jérôme during the monthly @ArollaFr’s Code Jam, and we made important changes in the code.</p>
<p>The concept of a Code Jam is simple : we meet once a month to practice our coding skills, emphasizing practices such as TDD and pair-programming.<br />For more details (in French) : <a title="http://www.arolla.fr/evenements-2/jams-de-code/" href="http://www.arolla.fr/evenements-2/jams-de-code/">http://www.arolla.fr/evenements-2/jams-de-code/</a></p>
<p>June’s theme was “Testing things that are difficult to test”. The session started with a “Lightning talk” by @cyriux, describing several situations where testing can be quite complicated, as for instance :</p>
<ul>
<li>When time is involved
<li>When parallelization and multi-threading is involved
<li>When architecture is involved (network bandwidth, fault-tolerant systems)
<li>Testing security (SQL injection, various kinds of exploits)
<li>When the host is difficult to emulate (as example: how to test an eclipse plug-in ?)
<li>Testing with non-trivial outputs/inputs: images, sounds, documents, reports, big messages…
<li>Testing with large configuration problems: realistic search index, social algorithms, time series for financial analytics…</li>
</ul>
<p>After this introduction, we were looking for a practical example of such a situation, and I suggested we could take a look at my implementation of this Linq provider. I haven’t gone very far yet, but my goal with this Linq to web service provider is to make the service return filtered data based on the Linq query. This means that I want the filtering to happen inside the web service, and not on the client side. And this is of course a behaviour that I want to test:</p>
<p><img style="display: block; float: none; margin-left: auto; margin-right: auto" src="http://www.pirrmann.net/wp-content/uploads/2012/06/linq-provider-schema-006.png"></p>
<p>After some discussion, @cyriux pointed to me that there were several false assumptions in the way I was testing things. I assumed I would be testing the provider by using it against a service that I had built myself… but I had no need for an actual web service implementation ! The service and the provider are two separate features, and mustn&#8217;t be unit-tested at the same time.</p>
<p>I have not completely given up the idea of implementing the service, but it is now a separate objective that has nothing to do with the provider implementation. And the fact that the service is a web service is just an implementation detail. My vision of the way to organize the project is now the following :</p>
<p><img style="display: block; float: none; margin-left: auto; margin-right: auto" src="http://www.pirrmann.net/wp-content/uploads/2012/07/linq-provider-schema-007.png"></p>
<p>The solution is now only composed of 3 assemblies :</p>
<ul>
<li>PeopleFinder, which defines the service interface (i.e. the contract) and POCOs used as simple Data Transfer Objects,
<li>LinqToService, which contains the actual implementation of the Linq provider,
<li>UnitTests, which contains the tests and a “lambda-based” implementation of the PeopleFinder interface.</li>
</ul>
<p>This organisation allows us to test only the behaviour of the provider, providing our own implementation of the service. To do so, we introduced a PeopleFinderLocator class. This might change in the future, but is quite out of scope here…</p>
<p>Given a query expression, the Linq provider’s goal is just to give the service the good parameters, and perform additional work that the service cannot handle. Here, the service knows how to filter the people based on their age. Let’s consider the following query :</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">var query = new QueryableServiceData&lt;Person&gt;()
    .Where(p =&gt; p.Age &gt;= 36);
</pre>
<p>When executing it, the provider must call the service with the appropriate parameter, and mustn’t do any additional work except handling the result back to the caller. The situation should be the following :</p>
<p><img style="width: 480px; display: block; float: none; margin-left: auto; margin-right: auto" src="http://www.pirrmann.net/wp-content/uploads/2012/07/linq-provider-schema-009.png"></p>
<p>And here is a test corresponding to this situation :</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">[TestMethod]
public void GivenAProviderWhenIFilterOnAgeGT36ThenItFilters()
{
    LambdaBasedPeopleFinder peopleFinder =
        new LambdaBasedPeopleFinder(p =&gt; p.Age &gt;= 36);
    PeopleFinderLocator.Instance = peopleFinder;

    QueryableServiceData&lt;Person&gt; people =
        new QueryableServiceData&lt;Person&gt;();

    var query = people
        .Where(p =&gt; p.Age &gt;= 36);

    var results = query.ToList();

    Assert.IsTrue(results.All(p =&gt; p.Age &gt;= 36));
    Assert.AreEqual(
        new IntCriterion()
            {
                FilterType = NumericFilterType.IsGreaterThan,
                Value = 36
            },
            peopleFinder.PassedCriteria.Age);
}</pre>
<p>In the previous test, we use a LambdaBasedPeopleFinder implementation of the service, that actually filters some sample data based on a predicate. In some way we rely on this implementation because we test that the results are correctly filtered. But we can even test that the provider doesn’t do the service’s work !</p>
<p>If we adapt the previous test by replacing the lambda by p =&gt; true, the results returned by the service will not be filtered, and we can test that the provider correctly delegates the work to the service, and doesn’t filter the data.</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">[TestMethod]
public void WhenIFilterOnAgeGT36ThenTheProviderDoesntFilter()
{
    LambdaBasedPeopleFinder peopleFinder =
        new LambdaBasedPeopleFinder(p =&gt; true);
    PeopleFinderLocator.Instance = peopleFinder;

    QueryableServiceData&lt;Person&gt; people =
        new QueryableServiceData&lt;Person&gt;();

    var query = people
        .Where(p =&gt; p.Age &gt;= 36);

    var results = query.ToList();

    Assert.IsFalse(results.All(p =&gt; p.Age &gt;= 36));
    Assert.AreEqual(
        new IntCriterion()
        {
            FilterType = NumericFilterType.IsGreaterThan,
            Value = 36
        },
        peopleFinder.PassedCriteria.Age);
}</pre>
<p>Finally, testing the provider was not a complicated question. My problem was not “how to test”, but rather “what to test”. </p>
<p>To finish, here are the next things that I want to do about this project :</p>
<ul>
<li>Use <a href="http://specflow.org/" target="_blank">SpecFlow</a> to transform all my tests and use <a href="https://github.com/cucumber/cucumber/wiki/Gherkin" target="_blank">the Gherkin syntax</a>,
<li>Handle more complex queries, list all the type of nodes that can be found and handle them, ensuring the correctness of the returned data. If needed, any unhandled node type would result in using a blank SearchCriteria object and performing all the work using Linq to Objects,
<li>Implement the service, even if it’s not necessary, just for the sake of it,
<li>Get stuck manipulating expression tress,
<li>Push the whole thing to a Github repository,
<li><u>Get help from anyone motivated</u>.</li>
</ul>
<img src="http://feeds.feedburner.com/~r/pirrmann/~4/1tTLOKObiQE" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.pirrmann.net/linq-provider-an-attempt-part-6/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.pirrmann.net/linq-provider-an-attempt-part-6/</feedburner:origLink></item>
		<item>
		<title>Linq provider : an attempt… part 5</title>
		<link>http://feedproxy.google.com/~r/pirrmann/~3/kGPPwlMxE5A/</link>
		<comments>http://www.pirrmann.net/linq-provider-an-attempt-part-5/#comments</comments>
		<pubDate>Wed, 06 Jun 2012 21:41:05 +0000</pubDate>
		<dc:creator>Pierre IRRMANN</dc:creator>
				<category><![CDATA[LINQ]]></category>
		<category><![CDATA[AST]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[CSS3]]></category>
		<category><![CDATA[HTML]]></category>
		<category><![CDATA[LINQ Provider]]></category>

		<guid isPermaLink="false">http://www.pirrmann.net/?p=116</guid>
		<description><![CDATA[Improving the toolbox : building our own expression tree visualizations In the last two posts, I included sample visualizations of expression trees. I’ve built these using a visitor pattern, that produces HTML markup. This is a good example of the &#8230; <a href="http://www.pirrmann.net/linq-provider-an-attempt-part-5/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<h3>Improving the toolbox : building our own expression tree visualizations</h3>
<p>In the last two posts, I included sample visualizations of expression trees. I’ve built these using a visitor pattern, that produces HTML markup. This is a good example of the use of this pattern, so I’ll try to explain how it allows us to work with expression trees.</p>
<p>The expression tree visualization that I build is based on HTML / CSS3, using the code provided at <a href="http://thecodeplayer.com/walkthrough/css3-family-tree" target="_blank">http://thecodeplayer.com/walkthrough/css3-family-tree</a>. Basically, the markup is formed of unordered lists (“ul / li” tags) that contains nested lists. You can view the generated HTML source by inspecting the DOM in the previous post.</p>
<p>The visualization builder is a class called TreeVisualizer, inheriting from ExpressionVisitor :</p>
<pre class="brush: csharp; gutter: false; toolbar: false;"><p>internal class TreeVisualizer : ExpressionVisitor
{
    private StringBuilder builder;
    private HtmlTextWriter writer;

    private TreeVisualizer()
    {
        this.builder = new StringBuilder();
        this.writer = new HtmlTextWriter(
            new StringWriter(
                this.builder,
                CultureInfo.InvariantCulture),
            "    ");
    } [...]</p></pre>
<p>The constructor is private, the only way to use this class is through a static method called BuildVisualization :</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">internal static string BuildVisualization(Expression expression)
{
    TreeVisualizer visualizer = new TreeVisualizer();
    visualizer.Visit(expression);
    return visualizer.Visualization;
}</pre>
<p>The returned property, Visualization, is defined this way :</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">public string Visualization
{
    get
    {
        return this.builder.ToString();
    }
}</pre>
<p>The class uses also two utility methods :</p>
<ul>
<li>GetSimplifiedType, which gives a user-friendly string representation of a given type.</li>
</ul>
<pre class="brush: csharp; gutter: false; toolbar: false;">private string GetSimplifiedType(Type type)
{
    if (!type.IsGenericType)
        return type.Name;

    string genericName = type.Name.Split('`').First();

    string genericArguments = string.Join(
        ", ",
        type.GenericTypeArguments.Select(
            t =&gt; GetSimplifiedType(t)));

    return string.Format(
        "{0}&lt;{1}&gt;",
        genericName,
        genericArguments);
}</pre>
<ul>
<li>VisitAndBuildTree, which adds content to the HtmlTextWriter based on the tree nodes that it visits :</li>
</ul>
<pre class="brush: csharp; gutter: false; toolbar: false;">private Expression VisitAndBuildTree(
    string nodeName,
    string nodeType,
    string nodeDescription,
    Func&lt;Expression&gt; childrenVisitorFunction = null)
{
    this.writer.RenderBeginTag("li");
    this.writer.WriteLine();
    this.writer.Indent++;

    this.writer.AddAttribute("href", "#");
    this.writer.RenderBeginTag("a");

    this.writer.AddAttribute("class", "node-name");
    this.writer.RenderBeginTag("span");
    this.writer.WriteEncodedText(nodeName);
    this.writer.RenderEndTag();
    this.writer.WriteBreak();

    if (!string.IsNullOrEmpty(nodeType))
    {
        this.writer.AddAttribute("class", "node-type");
        this.writer.RenderBeginTag("span");
        this.writer.WriteEncodedText(nodeType);
        this.writer.RenderEndTag();
        this.writer.WriteBreak();
    }

    this.writer.WriteEncodedText(nodeDescription);
    this.writer.RenderEndTag();
    this.writer.WriteLine();

    Expression baseReturn = null;
    if (childrenVisitorFunction != null)
    {
        this.writer.RenderBeginTag("ul");
        this.writer.WriteLine();
        this.writer.Indent++;

        baseReturn = childrenVisitorFunction();

        this.writer.Indent--;
        this.writer.RenderEndTag();
        this.writer.WriteLine();

    }

    this.writer.Indent--;
    this.writer.RenderEndTag();
    this.writer.WriteLine();

    return baseReturn;
}</pre>
<p>With the two previous functions, we can now override each Visit<em>SomeTypeOfNode</em> method and insert the appropriate details in the HTML. For instance :</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">protected override Expression VisitBinary(
    BinaryExpression node)
{
    return VisitAndBuildTree(
        "Binary",
        string.Empty,
        node.NodeType.ToString(),
        () =&gt; base.VisitBinary(node));
}</pre>
<pre class="brush: csharp; gutter: false; toolbar: false;">protected override Expression VisitLambda&lt;T&gt;(
    Expression&lt;T&gt; node)
{
    return VisitAndBuildTree(
        "Lambda",
        GetSimplifiedType(node.Type),
        node.ToString(),
        () =&gt; base.VisitLambda&lt;T&gt;(node));
}</pre>
<pre class="brush: csharp; gutter: false; toolbar: false;">protected override Expression VisitMethodCall(
    MethodCallExpression node)
{
    return VisitAndBuildTree(
        "Call",
        GetSimplifiedType(node.Type),
        node.Method.Name,
        () =&gt; base.VisitMethodCall(node));
}</pre>
<p>There are many methods, I’m not going to show them all here. I’ll just finish with a special one, VisitConstant. For this one, I just handled two special cases, when the constant is an IEnumerable, or when it is a string. This allows us to see the constants values for simple types in the tree, and a simplified type description if it is a generic IEnumerable.</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">protected override Expression VisitConstant(
    ConstantExpression node)
{
    string type = GetSimplifiedType(node.Type);

    string value;
    if (node.Type.IsGenericType
        &amp;&amp; node.Type.FindInterfaces(
            (t, o) =&gt; t.Name.StartsWith("IEnumerable"),
            true).Any())
    {
        value = type;
    }
    else if(type == "String")
    {
        value = string.Concat(
            "\"",
            ((string)node.Value).Replace("\"", "\\\""),
            "\"");
    }
    else
    {
        value = node.Value.ToString();
    }

    VisitAndBuildTree(
        "Constant",
        type,
        value);
    return base.VisitConstant(node);
}</pre>
<p>That’s all for tonight !</p>
<img src="http://feeds.feedburner.com/~r/pirrmann/~4/kGPPwlMxE5A" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.pirrmann.net/linq-provider-an-attempt-part-5/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.pirrmann.net/linq-provider-an-attempt-part-5/</feedburner:origLink></item>
		<item>
		<title>Linq provider : an attempt… part 4</title>
		<link>http://feedproxy.google.com/~r/pirrmann/~3/mjyL-vIy7FM/</link>
		<comments>http://www.pirrmann.net/linq-provider-an-attempt-part-4/#comments</comments>
		<pubDate>Wed, 06 Jun 2012 20:22:44 +0000</pubDate>
		<dc:creator>Pierre IRRMANN</dc:creator>
				<category><![CDATA[LINQ]]></category>
		<category><![CDATA[AST]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[LINQ Provider]]></category>

		<guid isPermaLink="false">http://www.pirrmann.net/?p=105</guid>
		<description><![CDATA[Using the Visitor pattern to manipulate expression trees In the previous posts of this series, I started to describe a partial implementation of a Linq provider. The aim of this provider is to get data from a service, and in &#8230; <a href="http://www.pirrmann.net/linq-provider-an-attempt-part-4/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<h3></h3>
<h3>Using the Visitor pattern to manipulate expression trees</h3>
<p>In the previous posts of this series, I started to describe a partial implementation of a Linq provider. The aim of this provider is to get data from a service, and in order to actually return that data to the caller, it implies some expression tree manipulations. After we obtained the data from the service, we want to inject an access to that actual data in the query expression tree, instead of the <em>QueryableDummyData&lt;Person&gt;</em> instance, which is in fact only a placeholder.</p>
<p>In order to replace that <em>QueryableDummyData&lt;Person&gt; </em>by a <em>Person[] </em>array, we use a class called <em>ExpressionTreeConstantReplacer</em>, which derives from the .NET 4.0 built-in <em>ExpressionVisitor</em> class, which in turn is based upon the Visitor pattern.</p>
<p>Applied to expression trees, the Visitor pattern can be used to generate an expression tree from the visited one, to accumulate some data while visiting the tree, or even both at the same time. Each visit method overload returns an expression, which is by default the unchanged expression it has just visited. It can return a new tree, but is should not modify the visited expression. This approach has the advantage to have no side-effect on the visited expression tree.</p>
<p>As a sample, the visitor pattern can be used to transform the following expression tree :</p>
<div style="border-bottom: black 1px solid; border-left: black 1px solid; overflow-x: auto; overflow-y: hidden; margin-bottom: 15px; height: 530px; border-top: black 1px solid; border-right: black 1px solid" class="syntaxtree">
<div style="width: 800px">
<ul>
<li><a href="#"><span class="node-name">Call</span><br /><span class="node-type">IQueryable&lt;Person&gt;</span><br />Where</a>
<ul>
<li><a href="#"><span class="node-name">Call</span><br /><span class="node-type">IQueryable&lt;Person&gt;</span><br />Where</a>
<ul>
<li><a href="#"><span class="node-name">Constant</span><br /><span class="node-type">QueryableDummyData&lt;Person&gt;</span><br />QueryableDummyData&lt;Person&gt;</a>
<li><a href="#"><span class="node-name">Lambda</span><br /><span class="node-type">Func&lt;Person, Boolean&gt;</span><br />p =&gt; (p.Age &gt;= 21)</a>
<ul>
<li><a href="#"><span class="node-name">Binary</span><br />GreaterThanOrEqual</a>
<ul>
<li><a href="#"><span class="node-name">Member</span><br /><span class="node-type">Int32</span><br />Age</a>
<ul>
<li><a href="#"><span class="node-name">Parameter</span><br /><span class="node-type">Person</span><br />p</a> </li>
</ul>
<li><a href="#"><span class="node-name">Constant</span><br /><span class="node-type">Int32</span><br />21</a> </li>
</ul>
<li><a href="#"><span class="node-name">Parameter</span><br /><span class="node-type">Person</span><br />p</a> </li>
</ul>
</li>
</ul>
<li><a href="#"><span class="node-name">Lambda</span><br /><span class="node-type">Func&lt;Person, Boolean&gt;</span><br />p =&gt; p.FirstName.StartsWith(&#8220;S&#8221;)</a>
<ul>
<li><a href="#"><span class="node-name">Call</span><br /><span class="node-type">Boolean</span><br />StartsWith</a>
<ul>
<li><a href="#"><span class="node-name">Member</span><br /><span class="node-type">String</span><br />FirstName</a>
<ul>
<li><a href="#"><span class="node-name">Parameter</span><br /><span class="node-type">Person</span><br />p</a> </li>
</ul>
<li><a href="#"><span class="node-name">Constant</span><br /><span class="node-type">String</span><br />&#8220;S&#8221;</a> </li>
</ul>
<li><a href="#"><span class="node-name">Parameter</span><br /><span class="node-type">Person</span><br />p</a> </li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<p>to this expression tree, which is the same but without the p =&gt; p.Age &gt;= 21 where clause :</p>
<div style="border-bottom: black 1px solid; border-left: black 1px solid; overflow-x: auto; overflow-y: hidden; margin-bottom: 15px; height: 430px; border-top: black 1px solid; border-right: black 1px solid" class="syntaxtree">
<div style="margin: auto; width: 500px">
<ul>
<li><a href="#"><span class="node-name">Call</span><br /><span class="node-type">IQueryable&lt;Person&gt;</span><br />Where</a>
<ul>
<li><a href="#"><span class="node-name">Constant</span><br /><span class="node-type">QueryableDummyData&lt;Person&gt;</span><br />QueryableDummyData&lt;Person&gt;</a>
<li><a href="#"><span class="node-name">Lambda</span><br /><span class="node-type">Func&lt;Person, Boolean&gt;</span><br />p =&gt; p.FirstName.StartsWith(&#8220;S&#8221;)</a>
<ul>
<li><a href="#"><span class="node-name">Call</span><br /><span class="node-type">Boolean</span><br />StartsWith</a>
<ul>
<li><a href="#"><span class="node-name">Member</span><br /><span class="node-type">String</span><br />FirstName</a>
<ul>
<li><a href="#"><span class="node-name">Parameter</span><br /><span class="node-type">Person</span><br />p</a> </li>
</ul>
<li><a href="#"><span class="node-name">Constant</span><br /><span class="node-type">String</span><br />&#8220;S&#8221;</a> </li>
</ul>
<li><a href="#"><span class="node-name">Parameter</span><br /><span class="node-type">Person</span><br />p</a> </li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<p>The <em>ExpressionVisitor</em> class is meant to be derived from, in order to create tree-manipulation classes. When the <em>ExpressionVisitor</em>’s Visit method is called, it determines the type of the node given as an entry parameter, and recursively visits the node and all his children, using each time the method corresponding to the node’s type.</p>
<p>This allows the developer of a derived class to override only the methods that needs to be. For instance, as we want to replace a Constant node with an other one, the class <em>ExpressionTreeConstantReplacer</em> derives from <em>ExpressionVisitor</em> and overrides the method VisitConstant.</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">internal class ExpressionTreeConstantReplacer&lt;TReplacement&gt;
    : ExpressionVisitor
{
    private Type originalType;
    private TReplacement replacementConstant;

    internal ExpressionTreeConstantReplacer(
        Type originalType, TReplacement replacementConstant)
    {
        this.originalType = originalType;
        this.replacementConstant = replacementConstant;
    }

    protected override Expression VisitConstant(
        ConstantExpression c)
    {
        if (c.Type == this.originalType)
            return Expression.Constant(this.replacementConstant);
        else
            return c;
    }
}</pre>
<p>The constructor of this class takes two arguments : the type of the original constant to replace, and the new value. Then during the expression tree visiting process, when a node of type Constant is detected, the VisitConstant method is called, and if its type matches the type to replace, a new Constant node encapsulating the replacement value is returned.</p>
<p>In order to make the replacement call more expressive, a helper class is also introduced, in order to take advantage of C#’s type inference, which is available on static methods but not on constructors :</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">internal class ExpressionTreeConstantReplacer
{
    internal static Expression CopyAndReplace&lt;TReplacement&gt;(
        Expression expression,
        Type originalType,
        TReplacement replacementConstant)
    {
        var modifier =
            new ExpressionTreeConstantReplacer&lt;TReplacement&gt;(
                originalType,
                replacementConstant);
        return modifier.Visit(expression);
    }
}</pre>
<p>This is what allows us to write the final replacement call this way :</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">Expression finalExpressionTree =
    ExpressionTreeConstantReplacer
        .CopyAndReplace(
            filteredExpressionTree,
            typeof(QueryableDummyData&lt;Person&gt;),
            queryablePersons);</pre>
<p>Next time, I’ll describe the TreeVisualizer class I wrote to generate the expression trees visualizations in this post.</p>
<img src="http://feeds.feedburner.com/~r/pirrmann/~4/mjyL-vIy7FM" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.pirrmann.net/linq-provider-an-attempt-part-4/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.pirrmann.net/linq-provider-an-attempt-part-4/</feedburner:origLink></item>
	</channel>
</rss>
