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

<channel>
	<title>Andrey Shchekin &#187; C# 3.0</title>
	<atom:link href="http://blog.ashmind.com/category/net/c/c-30/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.ashmind.com</link>
	<description></description>
	<lastBuildDate>Mon, 15 Mar 2010 18:00:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.1</generator>
		<item>
		<title>NMock 3.5</title>
		<link>http://blog.ashmind.com/2007/09/23/nmock-35/</link>
		<comments>http://blog.ashmind.com/2007/09/23/nmock-35/#comments</comments>
		<pubDate>Sun, 23 Sep 2007 09:09:14 +0000</pubDate>
		<dc:creator>Andrey Shchekin</dc:creator>
				<category><![CDATA[C# 3.0]]></category>
		<category><![CDATA[Fluent]]></category>
		<category><![CDATA[Mocking]]></category>
		<category><![CDATA[NMock2]]></category>

		<guid isPermaLink="false">http://blog.ashmind.com/index.php/2007/09/23/nmock-35/</guid>
		<description><![CDATA[One of the places where I am likely to actively use expression trees is testing/mocking. (I am not the first one to notice this — I saw some post on expression tree asserts, but I lost it). In my day-to-day development I am using NMock2. Ayende&#8216;s Rhino Mocks may be more convenient, but I do [...]]]></description>
			<content:encoded><![CDATA[<p>One of the places where I am likely to actively use expression trees is testing/mocking.<br />
(I am not the first one to notice this — I saw some post on expression tree asserts, but I lost it).</p>
<p>In my day-to-day development I am using <a href="http://nmock.org">NMock2</a>.<br /> <a href="http://www.ayende.com/Blog/">Ayende</a>&#8216;s <a href="http://www.ayende.com/projects/rhino-mocks.aspx">Rhino Mocks</a> may be more convenient, but I do not like the syntax.<br /> I just can&#8217;t read &#8220;expect call return&#8221; — my mind wants &#8220;expect call returns&#8221;.<br /> Also, event support in Rhinos is really cryptic.<br /> (I understand that it may be the only stringless way to express it).</p>
<p>So working on C# 3.0 project, I&#8217;ve looked into a stringless experience with NMock2.<br /> What I wanted was to pass a method call expression, to change this:
<pre class="csharpcode">
<span class="cls">Expect</span>.Once.On(fs)
    .Method(<span class="str">"GetDescendantDirectories"</span>)
    .With(RootPath)
    .Will(<span class="cls">Return</span>.Value(directories));</pre>
<p>into this
<pre class="csharpcode">
<span class="cls">Expect</span>.Once
    .That(() =&gt; fs.GetDescendantDirectories(RootPath))
    .Will(<span class="cls">Return</span>.Value(directories));</pre>
</p>
<p>Fortunately, it was quite easy to do with extension methods.<br />
I have spent more time figuring better fluent syntax than actually writing it.</p>
<p>But the case where expression trees really shine, I think, is in the possibility to do this:</p>
<pre class="csharpcode">
<span class="cls">Expect</span>.Exactly(directory.Files.Count)
    .That(() =&gt; access.IsPublicFile(<em><span class="cls">Any</span>.String</em>))
    .Will(<span class="cls">Return</span>.Value(<span class="kwrd">true</span>));</pre>
<p>I can analyze expression tree and find out that Any.String is not &#8220;a string&#8221;, but &#8220;any string&#8221;.<br />
It is also easy to imagine Any.String.Matching(&#8220;^whatever&#8221;) and so on.<br />
I have <strong>not</strong> tried to implement it, but I feel that it would be simple as well.
</p>
<p>Also, while writing the post, I just got an idea — in the world of extenson methods we can do</p>
<pre class="csharpcode">
<span class="cls">Expect</span>.Exactly(directory.Files.Count)
    .That(() =&gt; access.IsPublicFile(<span class="cls">Any</span>.String))
    .Will<em>.Return(<span class="kwrd">true</span>)</em>;</pre>
<p>without sacrificing extensibility.<br />
&#8220;Will&#8221; can also be chained if more than one action is needed (however, a delegate would be better for this).</p>
<p>It would be nice to actually add this to NMock2 (as 3.5 branch), but they are using CVS, not SVN.<br />
Also, am I the only one who thinks that SourceForge is slow and has hardly usable (bloated) design?</p>
<p>So if you want the code, you can ask me in comments, but it is primitive indeed.</p>
<style type="text/css">
.codewrap pre { width: 1%; }
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: Consolas, "Courier New", Courier, Monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .cls { color: #2b91af; }
.csharpcode em { font-weight: normal; font-style: normal; text-decoration: underline; }
</style>
]]></content:encoded>
			<wfw:commentRss>http://blog.ashmind.com/2007/09/23/nmock-35/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Simple typeswitch in C# 3.0, Part 2: The Solutions</title>
		<link>http://blog.ashmind.com/2007/09/20/simple-typeswitch-in-c-30-part-2-the-solutions/</link>
		<comments>http://blog.ashmind.com/2007/09/20/simple-typeswitch-in-c-30-part-2-the-solutions/#comments</comments>
		<pubDate>Thu, 20 Sep 2007 19:58:38 +0000</pubDate>
		<dc:creator>Andrey Shchekin</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[C# 3.0]]></category>

		<guid isPermaLink="false">http://blog.ashmind.com/index.php/2007/09/20/simple-typeswitch-in-c-30-part-2-the-solutions/</guid>
		<description><![CDATA[.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #a31515; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } [...]]]></description>
			<content:encoded><![CDATA[<style type="text/css">.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #a31515; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
.csharpcode .cls { color: #2b91af; }
</style>
<p>Some days ago I wrote an <a href="http://blog.ashmind.com/index.php/2007/09/12/simple-typeswitch-in-c-30-part-1-the-problem/">overview of typeswitch problem</a>.<br />Now it&#8217;s time to give some solutions.</p>
<h4>Overview</h4>
<p>Let&#8217;s imagine a document inheritance hierarchy:
<pre class="csharpcode"><span class="cls">XsltDocument</span> : <span class="cls">XmlDocument</span> : <span class="cls">Document</span>
<span class="cls">TextDocument</span> : <span class="cls">Document</span></pre>
<p>Let&#8217;s assume I want to get strings <span class="csharpcode"><span class="str">&#8220;Xml&#8221;</span>, <span class="str">&#8220;Xslt&#8221;</span>, <span class="str">&#8220;Not Xml and not Xslt&#8221;</span></span> based on the document runtime type.<br />This is primitive indeed, but it does demonstrate a concept.</p>
<p>I call the most useful soultion <em>fluent switch</em>:</p>
<pre class="csharpcode"><span class="kwrd">string</span> result = <span class="cls">Switch</span>.Type(document).
        Case(
            (<span class="cls">XsltDocument</span> d) =&gt; <span class="str">"Xslt"</span>
        ).
        Case(
            (<span class="cls">XmlDocument</span> d) =&gt; <span class="str">"Xml"</span>
        ).
        Otherwise(
            d =&gt; <span class="str">"Not Xml and not Xslt"</span>
        ).
        Result;</pre>
<p>It does contain a lot of visual clutter, but it scales quite well in comparison to if/return approach.<br />The code behind is simple — each Case checks type and returns itself.<br />Case is a generic method whose parameters are inferred from the lambda.</p>
<p>For this task, case bodies do not depend on actual object contents.<br />So they can be expressed cleaner:</p>
<pre class="csharpcode"><span class="kwrd">string</span> result = <span class="cls">Switch</span>.Type(document).To&lt;<span class="kwrd">string</span>&gt;().
        Case&lt;<span class="cls">XsltDocument</span>&gt;(<span class="str">"Xslt"</span>).
        Case&lt;<span class="cls">XmlDocument</span>&gt;(<span class="str">"Xml"</span>).
        Otherwise(<span class="str">"Not Xml and not Xslt"</span>).
        Result;</pre>
<p>This time I have to specify the result type explicitly.</p>
<p>The fluent switch syntax is quite powerful — you can even add cases dynamically.<br />This is a nice difference from conventional language constructs.</p>
<h4>Alternatives</h4>
<p>I have tried a number of alternatives, but no one of them did better.</p>
<ol>
<li><strong>Many overloads switch</strong>
<pre class="csharpcode"><span class="kwrd">string</span> result = <span class="cls">Switch</span>.Type(
    document,
        (<span class="cls">XsltDocument</span> d) =&gt; <span class="str">"Xslt"</span>,
        (<span class="cls">XmlDocument</span> d) =&gt; <span class="str">"Xml"</span>,
        d =&gt; <span class="str">"Not Xml and not Xslt"</span>
);</pre>
<p>This syntax is quite concise and understandable.<br />But it requires an additional overload for each additional case.<br />So it is quite impractical.</p>
<li><strong>Object initializer switch</strong>
<pre class="csharpcode"><span class="kwrd">string</span> result = <span class="kwrd">new</span> <span class="cls">TypeSwitch</span>&lt;<span class="cls">Document</span>, <span class="kwrd">string</span>&gt;(document) {
    (<span class="cls">XsltDocument</span> d) =&gt; <span class="str">"Xslt"</span>,
    (<span class="cls">XmlDocument</span> d) =&gt; <span class="str">"Xml"</span>,
    d =&gt; <span class="str">"Not Xml and not Xslt"</span>
};</pre>
<p>Also more concise than my original solution, but much more cryptic.<br />Constructor and generic parameters also add a degree of confusion.</p>
<p>The most interesting thing about this syntax was that it actually worked.<br />It seems object initializers have some nice <em>fluent power</em>.</p>
</li>
</ol>
<h4>Compilation</h4>
<p>After running some benchmarks, I found that fluent switch is about 200 times slower than hardcoded ifs.<br />It may be perfectly acceptable, of course.<br />However, I have found a way to precompile the switch using expression trees.</p>
<p>From the usage perspective, precompiled switch is just a Func&lt;T, TResult&gt; (it does not support Actions right now).<br />So you can cache it in
<pre class="csharpcode"><span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">readonly</span> <span class="cls">Func</span>&lt;<span class="cls">Document</span>, <span class="kwrd">string</span>&gt; CompiledFluentLambdaSwitch = <span class="cls">Switch</span>.Type&lt;<span class="cls">Document</span>&gt;().To&lt;<span class="kwrd">string</span>&gt;().
    Case(
        (<span class="cls">XsltDocument</span> d) =&gt; <span class="str">"Xslt"</span>
    ).
    Case(
        (<span class="cls">XmlDocument</span> d) =&gt; <span class="str">"Xml"</span>
    ).
    Otherwise(
        d =&gt; <span class="str">"Not Xml and not Xslt"</span>
    ).
    Compile();</pre>
<p>which is extremely similar to the first code sample.<br />The differences are that you do not specify what you are switching on (it would be a function parameter).<br />But you do explicitly specify from/to types.</p>
<p>The compilation process was fun to write, since it was the first time I dug into expressions trees.<br />Statements are not supported in trees, so I had to use embedded ConditionalExpressions for cases.<br />The resulting tree is something like
<pre class="csharpcode">d =&gt; (d <span class="kwrd">is</span> <span class="cls">XsltDocument</span>)
             ? ((cast =&gt; <span class="str">"Xslt"</span>)(d <span class="kwrd">as</span> <span class="cls">XsltDocument</span>))
             : ((d <span class="kwrd">is</span> <span class="cls">XmlDocument</span>)
                   ? ((...</pre>
<p>I have not found a way to cache cast and null-check it, so I cast/typecheck it two times.</p>
<h4>Benchmarks</h4>
<p>The best thing about compilation is performance:</p>
<pre style="padding-right: 5px; padding-left: 5px; padding-bottom: 5px; width: 50em; color: white; padding-top: 5px; font-family: consolas, 'Courier New', courier; background-color: black">Benchmark: 1000000 iterations, two switch calls per iteration.

Benchmark overhead:            40.1ms   30.0ms   30.0ms   30.0ms |    32.5ms
<span style="color: yellow">Direct cast:                   80.1ms   60.1ms   80.1ms   60.1ms |    70.1ms</span>
Fluent switch
    on lambdas:              1512.2ms 1502.2ms 1602.3ms 1482.1ms |  1524.7ms
    <span style="color: yellow">on lambdas (compiled):     90.1ms  110.2ms   80.1ms   80.1ms |    90.1ms</span>
    on constants:            1281.8ms 1271.8ms 1311.9ms 1271.8ms |  1284.3ms
    <span style="color: yellow">on constants (compiled):   80.1ms   90.1ms   90.1ms   70.1ms |    82.6ms</span>
Many overloads switch:        440.6ms  390.6ms  430.6ms  420.6ms |   420.6ms
Object initializer switch:    751.1ms  681.0ms  741.1ms  751.1ms |   731.1ms</pre>
<p>As you can see, precompiled switch is nearly as performant as hardcoded one (direct cast).<br />I am quite impressed by simplicity/power ratio of the expression trees.</p>
<h4 id="typeswitch-2-code">Code</h4>
<p>I uploaded AshMind.Constructs to <a href="http://code.google.com/p/ashmind-constructs/">Google Code</a>.<br />I see it as a learning/research project, but you can put it to any practical use.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.ashmind.com/2007/09/20/simple-typeswitch-in-c-30-part-2-the-solutions/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Expression tree limitations in C# 3.0</title>
		<link>http://blog.ashmind.com/2007/09/07/expression-tree-limitations-in-c-30/</link>
		<comments>http://blog.ashmind.com/2007/09/07/expression-tree-limitations-in-c-30/#comments</comments>
		<pubDate>Fri, 07 Sep 2007 20:57:35 +0000</pubDate>
		<dc:creator>Andrey Shchekin</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[C# 3.0]]></category>
		<category><![CDATA[Reference]]></category>

		<guid isPermaLink="false">http://blog.ashmind.com/index.php/2007/09/07/expression-tree-limitations-in-c-30/</guid>
		<description><![CDATA[.csharpcode, .csharpcode pre { font-size: small; color: black; font-family: Consolas, "Courier New", Courier, Monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } [...]]]></description>
			<content:encoded><![CDATA[<style type="text/css">.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: Consolas, "Courier New", Courier, Monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }
</style>
<p style="font-size: 80%">Everything in this article is tested with Visual Studio 2008 Beta 2 and may become obsolete.</p>
<p>While a lot of people blog about expression trees in new C#, I haven&#8217;t seen any post about things you <em>can not</em> do with them. Maybe it is common knowledge,&nbsp;but since&nbsp;I stumbled in it myself, I&#8217;ll share.</p>
<p>Basically, C# specification says:<br />
<blockquote>Not all anonymous functions can be represented as expression trees. For instance, anonymous functions with statement bodies, and anonymous functions containing assignment expressions cannot be represented. In these cases, a conversion still exists, but will fail at compile time.</p></blockquote>
<p>So, that&#8217;s&nbsp;what you can not do according to the specification:</p>
<blockquote><pre class="csharpcode">
Expression&lt;…&gt; y = x =&gt; { DoAnything() };
<span class="rem">// error CS0834: A lambda expression with a statement body cannot be converted to an expression tree</span>

<span class="kwrd">int</span> z = 3;
Expression&lt;…&gt; y = () =&gt; z = z + 5;
<span class="rem">// error CS0832: An expression tree may not contain an assignment operator.</span>
</pre>
</blockquote>
<p>To find out other limitations, I&#8217;ve looked in Microsoft.NET\Framework\v3.5\1033\cscompui.dll file (that contains all string resources (errors/warnings) for csc compiler) and did a search on &#8220;expression tree&#8221;.</p>
<p>So there is a summary table of all compiler errors on expression trees with sample code for each case:</p>
<table>
<tr>
<th>Error code</th>
<th>Error message</th>
<th>Sample code</th>
</tr>
<tr>
<td>CS????</td>
<td>Partial methods with only a defining declaration or removed conditional methods cannot be used in expression trees.</td>
<td>I see no way to use partial in expression tree.<br /> Partial methods always return void, so they can be used only as a statement and not in a lambda with expression body.</td>
</tr>
<tr>
<td>CS0831</td>
<td>An expression tree may not contain a base access.</td>
<td>
<pre class="csharpcode">
Expression&lt;Func&lt;<span class="kwrd">string</span>&gt;&gt; y = () =&gt; <span class="kwrd">base</span>.ToString();</pre>
</td>
</tr>
<tr>
<td>CS0832</td>
<td>An expression tree may not contain an assignment operator.</td>
<td>See above.</td>
</tr>
<tr>
<td>CS0834</td>
<td>A lambda expression with a statement body cannot be converted to an expression tree.</td>
<td>See above.</td>
</tr>
<tr>
<td>CS0838</td>
<td>An expression tree may not contain a multidimensional array initializer.</td>
<td>
<pre class="csharpcode">
Expression&lt;Func&lt;<span class="kwrd">string</span>[,]&gt;&gt; y =
    () =&gt; <span class="kwrd">new</span> <span class="kwrd">string</span>[,] { { <span class="str">"A"</span>, <span class="str">"A"</span>} };</pre>
</td>
</tr>
<tr>
<td>CS0838</td>
<td>An expression tree may not contain an unsafe pointer operation.</td>
<td>No sample, I am not very friendly with unsafe syntax.</td>
</tr>
<tr>
<td>CS1945</td>
<td>An expression tree may not contain an anonymous method expression.</td>
<td>
<pre class="csharpcode">
Expression&lt;Func&lt;Func&lt;<span class="kwrd">string</span>&gt;&gt;&gt; y = () =&gt; <span class="kwrd">delegate</span> { <span class="kwrd">return</span> <span class="str">"hi"</span>; };
<span class="rem">// [NB] This woks just fine:</span>
Expression&lt;Func&lt;Func&lt;<span class="kwrd">string</span>&gt;&gt;&gt; y = () =&gt; () =&gt; <span class="str">"hi"</span>;</pre>
</td>
</tr>
<tr>
<td>CS1952</td>
<td>An expression tree lambda may not contain a method with variable arguments.</td>
<td>This one was tricky:</p>
<pre class="csharpcode">
<span class="kwrd">public</span> <span class="kwrd">string</span> ReturnHi(<span class="kwrd">__arglist</span>)
{
    <span class="kwrd">return</span> <span class="str">"hi"</span>;
}

<span class="kwrd">public</span> <span class="kwrd">void</span> Test()
{
    Expression&lt;Func&lt;<span class="kwrd">string</span>&gt;&gt; y =
        () =&gt; <span class="kwrd">this</span>.ReturnHi(<span class="kwrd">__arglist</span>(<span class="str">"stub1"</span>, <span class="str">"stub2"</span>));
}</pre>
</td>
</tr>
</table>
<p>There are several error messages other than the first one in a table that I can not produce at all.</p>
<table>
<tr>
<th>Error message</th>
<th>Comment</th>
</tr>
<tr>
<td>An expression tree lambda may not contain an out or ref parameter.</td>
<td>Lambdas indeed can not capture out and ref parameters, but the error in such case is <br />
CS1628: Cannot use ref or out parameter &#8216;…&#8217; inside an anonymous method, lambda expression, or query expression.<br />
I could not create any kind of lambda for the delegate type with out or ref parameter, not only expression tree.</td>
</tr>
<tr>
<td>An expression tree lambda may not contain a member group.</td>
<td>No problems creating lambdas that do any member group resolution. I have no idea how to put unresolved member group anywhere without getting it resolved.</td>
</tr>
</table>
]]></content:encoded>
			<wfw:commentRss>http://blog.ashmind.com/2007/09/07/expression-tree-limitations-in-c-30/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

