<?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>.Net Smoothie &#187; Extension Methods</title>
	<atom:link href="http://www.richardbushnell.net/category/extension-methods/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.richardbushnell.net</link>
	<description></description>
	<lastBuildDate>Wed, 30 Dec 2009 11:42:52 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>C# Acrobatics : Lambdas and Expression Methods as a replacement for NVelocity</title>
		<link>http://www.richardbushnell.net/2008/06/02/c-acrobatics-lambdas-and-expression-methods-as-a-replacement-for-nvelocity/</link>
		<comments>http://www.richardbushnell.net/2008/06/02/c-acrobatics-lambdas-and-expression-methods-as-a-replacement-for-nvelocity/#comments</comments>
		<pubDate>Mon, 02 Jun 2008 10:09:06 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[ASP.Net]]></category>
		<category><![CDATA[C# 3.0]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Extension Methods]]></category>
		<category><![CDATA[Lambda Expressions]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[ListView]]></category>
		<category><![CDATA[NVelocity]]></category>

		<guid isPermaLink="false">http://richardbushnell.net/index.php/2008/06/02/c-acrobatics-lambdas-and-expression-methods-as-a-replacement-for-nvelocity/</guid>
		<description><![CDATA[I&#8217;ve been very quiet recently. (I&#8217;m trying to not be so loud, Scott. ) You see, I&#8217;ve been writing a lot of ASP.Net code for a site I&#8217;m working on. And, to be honest, I&#8217;ve been having a lot of trouble. The source code for .Net has been very helpful, and I&#8217;ve learnt a lot [...]]]></description>
			<content:encoded><![CDATA[
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.richardbushnell.net%2F2008%2F06%2F02%2Fc-acrobatics-lambdas-and-expression-methods-as-a-replacement-for-nvelocity%2F&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="false" style="border:none; overflow:; width:450px; height:30px"></iframe>
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<br><p>I&#8217;ve been very quiet recently. (I&#8217;m trying to not be so <a href="http://www.hanselman.com/blog/ProfessionalismProgrammingAndPunditryAndSuccessAsAMetric.aspx" target="_blank">loud</a>, Scott. <img src='http://www.richardbushnell.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  ) You see, I&#8217;ve been writing a lot of ASP.Net code for a site I&#8217;m working on. And, to be honest, I&#8217;ve been having a <em>lot</em> of trouble. The <a href="http://richardbushnell.net/index.php/2008/04/18/the-value-of-being-free-to-see-the-source/" target="_blank">source code for .Net</a> has been very helpful, and I&#8217;ve learnt a lot about what&#8217;s going on under the covers of ASP.Net because of it. </p>
<p>(Note: I won&#8217;t comment here on the quality of the code I&#8217;ve found &#8211; I&#8217;ll leave that up to you to judge. But in any case, I&#8217;ve been trying to build on top of it.)</p>
<p>One thing I&#8217;ve found to be important is the reliance on Web Controls. (It&#8217;s got something to do with javascript libraries, but that&#8217;s another story.) Getting away from the &quot;standard&quot; way to do ASP.Net isn&#8217;t easy though. Even the ninjas on the <a href="http://www.haacked.com/archive/2008/05/31/the-design-is-never-right-the-first-time.aspx" target="_blank">ASP.Net MVC</a> team <a href="http://www.haacked.com/archive/2008/05/03/code-based-repeater-for-asp.net-mvc.aspx" target="_blank">seem to be having trouble</a>. However, with the magic of lambdas and extension methods in C#, I think I might have just about managed to get something usable. I thought I&#8217;d publish my work here, and see what comments I got.</p>
<p>I think it&#8217;s best to start with what my ASP.Net code looks like once I&#8217;ve got everything working. (Notice I still have some Web Controls in there, but that&#8217;s because I&#8217;ve not worked out how to do sorting of data without web controls yet.)</p>
<p>The inspiration for this was taken from the <a href="r" target="_blank">improvements made to NVelocity</a> by the gurus on the Castle Project. I thought it looked great, and I&#8217;d like something similar, but I didn&#8217;t really want to learn a whole new scripting language and integrate it into my working environment just for rendering a bit of HTML. So I built some C# classes to do a similar thing for me instead. It&#8217;s not as nice as NVelocity, but it&#8217;s okay for now.</p>
<p><strong>Warning</strong>: The following code may contain statements of a disturbing nature to more sensitive readers. We cannot be held responsible for any confusion, delusion or mental illness caused by this code.</p>
<p>It starts by taking a collection of Task objects, and calling the extension method &quot;ForEach&quot; on them:</p>
<pre class="code"><span style="background: #ffee62">&lt;%</span> Tasks.ForEach(sections =&gt; {
   sections.NoData = tasks =&gt; {
<span style="background: #ffee62">%&gt;
</span><span style="color: blue">   &lt;</span><span style="color: #a31515">p</span><span style="color: blue">&gt;
</span>   Hey, you've got nothing to do.<span style="color: blue">&lt;/</span><span style="color: #a31515">p</span><span style="color: blue">&gt;
   &lt;</span><span style="color: #a31515">p</span><span style="color: blue">&gt;
</span><span style="background: #ffee62">&lt;%
</span>   };
   sections.BeforeAll = tasks =&gt; {
   <span style="background: #ffee62">%&gt;
</span>  <span style="color: blue">&lt;</span><span style="color: #a31515">table </span><span style="color: red">class</span><span style="color: blue">=&quot;task-list&quot;&gt;
    &lt;</span><span style="color: #a31515">tr </span><span style="color: red">class</span><span style="color: blue">=&quot;task-list-header&quot;&gt;
      &lt;</span><span style="color: #a31515">th</span><span style="color: blue">&gt;
        &lt;</span><span style="color: #a31515">asp</span><span style="color: blue">:</span><span style="color: #a31515">LinkButton </span><span style="color: red">runat</span><span style="color: blue">=&quot;server&quot; </span><span style="color: red">CommandName</span><span style="color: blue">=&quot;Sort&quot; </span><span style="color: red">CommandArgument</span><span style="color: blue">=&quot;StartDate&quot;
          </span><span style="color: red">Text</span><span style="color: blue">=&quot;Started&quot; /&gt;
      &lt;/</span><span style="color: #a31515">th</span><span style="color: blue">&gt;
      &lt;</span><span style="color: #a31515">th</span><span style="color: blue">&gt;
        &lt;</span><span style="color: #a31515">asp</span><span style="color: blue">:</span><span style="color: #a31515">LinkButton </span><span style="color: red">runat</span><span style="color: blue">=&quot;server&quot; </span><span style="color: red">CommandName</span><span style="color: blue">=&quot;Sort&quot; </span><span style="color: red">CommandArgument</span><span style="color: blue">=&quot;DueOn&quot;
          </span><span style="color: red">Text</span><span style="color: blue">=&quot;Due&quot; /&gt;
      &lt;/</span><span style="color: #a31515">th</span><span style="color: blue">&gt;
      &lt;</span><span style="color: #a31515">th</span><span style="color: blue">&gt;
        &lt;</span><span style="color: #a31515">asp</span><span style="color: blue">:</span><span style="color: #a31515">LinkButton </span><span style="color: red">runat</span><span style="color: blue">=&quot;server&quot; </span><span style="color: red">CommandName</span><span style="color: blue">=&quot;Sort&quot; </span><span style="color: red">CommandArgument</span><span style="color: blue">=&quot;Priority&quot;
          </span><span style="color: red">Text</span><span style="color: blue">=&quot;Priority&quot; /&gt;
      &lt;/</span><span style="color: #a31515">th</span><span style="color: blue">&gt;
      &lt;</span><span style="color: #a31515">th</span><span style="color: blue">&gt;
        &lt;</span><span style="color: #a31515">asp</span><span style="color: blue">:</span><span style="color: #a31515">LinkButton </span><span style="color: red">CssClass</span><span style="color: blue">=&quot;task-description&quot; </span><span style="color: red">CommandName</span><span style="color: blue">=&quot;Sort&quot; </span><span style="color: red">CommandArgument</span><span style="color: blue">=&quot;Title&quot;
          </span><span style="color: red">Text</span><span style="color: blue">=&quot;Description&quot; </span><span style="color: red">runat</span><span style="color: blue">=&quot;server&quot; /&gt;
      &lt;/</span><span style="color: #a31515">th</span><span style="color: blue">&gt;</span><span style="color: blue">      &lt;</span><span style="color: #a31515">th</span><span style="color: blue">&gt;
      &lt;/</span><span style="color: #a31515">th</span><span style="color: blue">&gt;
    &lt;/</span><span style="color: #a31515">tr</span><span style="color: blue">&gt;
   </span><span style="background: #ffee62">&lt;%
</span>   };
     sections.Before = task =&gt; {
    <span style="background: #ffee62">%&gt;
</span>    <span style="color: blue">&lt;</span><span style="color: #a31515">tr </span><span style="color: red">class</span><span style="color: blue">=&quot;</span><span style="background: #ffee62">&lt;%</span>= this.tableCssClasses.Next() <span style="background: #ffee62">%&gt;</span><span style="color: blue">&quot;&gt;
    </span><span style="background: #ffee62">&lt;%
</span>   };
   sections.Each = task =&gt; {
    <span style="background: #ffee62">%&gt;</span>
    <span style="color: blue">&lt;</span><span style="color: #a31515">td</span><span style="color: blue">&gt;
      &lt;</span><span style="color: #a31515">div </span><span style="color: red">class</span><span style="color: blue">='calendar calendar-icon-</span><span style="background: #ffee62">&lt;%</span>= task.StartMonth <span style="background: #ffee62">%&gt;</span><span style="color: blue">'&gt;
        &lt;</span><span style="color: #a31515">div </span><span style="color: red">class</span><span style="color: blue">=&quot;calendar-day&quot;&gt;
          </span><span style="background: #ffee62">&lt;%</span><span style="color: blue">= </span>task.StartDayOfMonth <span style="background: #ffee62">%&gt;</span><span style="color: blue">&lt;/</span><span style="color: #a31515">div</span><span style="color: blue">&gt;
      &lt;/</span><span style="color: #a31515">div</span><span style="color: blue">&gt;
    &lt;/</span><span style="color: #a31515">td</span><span style="color: blue">&gt;
    &lt;</span><span style="color: #a31515">td</span><span style="color: blue">&gt;
      &lt;</span><span style="color: #a31515">div </span><span style="color: red">class</span><span style="color: blue">='calendar calendar-icon-</span><span style="background: #ffee62">&lt;%</span>= task.DueMonth <span style="background: #ffee62">%&gt;</span><span style="color: blue">'&gt;
        &lt;</span><span style="color: #a31515">div </span><span style="color: red">class</span><span style="color: blue">=&quot;calendar-day&quot;&gt;
          </span><span style="background: #ffee62">&lt;%</span><span style="color: blue">= </span>task.DueDayOfMonth <span style="background: #ffee62">%&gt;</span><span style="color: blue">&lt;/</span><span style="color: #a31515">div</span><span style="color: blue">&gt;
      &lt;/</span><span style="color: #a31515">div</span><span style="color: blue">&gt;
    &lt;/</span><span style="color: #a31515">td</span><span style="color: blue">&gt;
    &lt;</span><span style="color: #a31515">td</span><span style="color: blue">&gt;
      </span><span style="background: #ffee62">&lt;%</span><span style="color: blue">= </span>task.Priority <span style="background: #ffee62">%&gt;
</span>    <span style="color: blue">&lt;/</span><span style="color: #a31515">td</span><span style="color: blue">&gt;
    &lt;</span><span style="color: #a31515">td </span><span style="color: red">class</span><span style="color: blue">=&quot;task-title&quot;&gt;
      &lt;</span><span style="color: #a31515">a </span><span style="color: red">href</span><span style="color: blue">='</span><span style="background: #ffee62">&lt;%</span>= Href.For(&quot;~/Tasks/{0}/Show.aspx&quot;, task.ID) <span style="background: #ffee62">%&gt;</span><span style="color: blue">'&gt;</span><span style="background: #ffee62">&lt;%</span><span style="color: blue">= </span>task.Title <span style="background: #ffee62">%&gt;</span><span style="color: blue">&lt;/</span><span style="color: #a31515">a</span><span style="color: blue">&gt;
    &lt;/</span><span style="color: #a31515">td</span><span style="color: blue">&gt;
</span><span style="color: blue">    &lt;</span><span style="color: #a31515">td</span><span style="color: blue">&gt;
      &lt;</span><span style="color: #a31515">asp</span><span style="color: blue">:</span><span style="color: #a31515">Button </span><span style="color: red">ID</span><span style="color: blue">=&quot;Button1&quot; </span><span style="color: red">runat</span><span style="color: blue">=&quot;server&quot; </span><span style="color: red">CssClass</span><span style="color: blue">=&quot;button&quot; </span><span style="color: red">CommandName</span><span style="color: blue">=&quot;Delete&quot; </span><span style="color: red">Text</span><span style="color: blue">=&quot;Mark Done&quot; /&gt;
    &lt;/</span><span style="color: #a31515">td</span><span style="color: blue">&gt;
    </span><span style="background: #ffee62">&lt;%
</span>   };

   sections.After = task =&gt; {
    <span style="background: #ffee62">%&gt;
</span>    <span style="color: blue">&lt;/</span><span style="color: #a31515">tr</span><span style="color: blue">&gt;
    </span><span style="background: #ffee62">&lt;%
</span>   };

   sections.AfterAll = task =&gt; {
    <span style="background: #ffee62">%&gt;
</span>    <span style="color: blue">&lt;/</span><span style="color: #a31515">table</span><span style="color: blue">&gt;
    </span><span style="background: #ffee62">&lt;%
</span>   };
 });
<span style="background: #ffee62">%&gt;</span></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>It might take a while to grasp what&#8217;s going on here. The code actually starts using an Extension method to IEnumerable that looks like this:</p>
<pre class="code"><span style="color: gray">public static void </span>ForEach&lt;T&gt;(<span style="color: gray">this </span><span style="color: #2b91af">IEnumerable</span>&lt;T&gt; enumerable, <span style="color: #2b91af">ForeachSectionSetter</span>&lt;T&gt; sectionSetter) {
  <span style="color: gray">if </span>(enumerable != <span style="color: gray">null</span>) {

    <span style="color: gray">if </span>(sectionSetter != <span style="color: gray">null</span>) {
      <span style="color: #2b91af">ForeachSections</span>&lt;T&gt; sections = <span style="color: gray">new </span><span style="color: #2b91af">ForeachSections</span>&lt;T&gt;();
      sectionSetter(sections);

      <span style="color: gray">if </span>(enumerable.Count() == 0) {
        <span style="color: gray">if </span>(sections.NoData != <span style="color: gray">null</span>)
          sections.NoData(enumerable);
        <span style="color: gray">return</span>;
      }

      <span style="color: gray">if </span>(sections.BeforeAll != <span style="color: gray">null</span>)
        sections.BeforeAll(enumerable);

      <span style="color: gray">int </span>itemIndex = 0;
      T previousItem = <span style="color: gray">default</span>(T);

      <span style="color: gray">foreach </span>(T item <span style="color: gray">in </span>enumerable) {
        <span style="color: gray">if </span>(sections.Before != <span style="color: gray">null</span>)
          sections.Before(item);
        <span style="color: gray">if </span>(itemIndex % 2 == 1 &amp;&amp; sections.Odd != <span style="color: gray">null</span>)
          sections.Odd(item);
        <span style="color: gray">if </span>(itemIndex % 2 == 0 &amp;&amp; sections.Even != <span style="color: gray">null</span>)
          sections.Even(item);
        <span style="color: gray">if </span>(itemIndex &gt; 0 &amp;&amp; sections.Between != <span style="color: gray">null</span>)
          sections.Between(previousItem, item);
        <span style="color: gray">if </span>(sections.Each != <span style="color: gray">null</span>)
          sections.Each(item);
        <span style="color: gray">if </span>(sections.After != <span style="color: gray">null</span>)
          sections.After(item);
        itemIndex++;
        previousItem = item;
      }
      <span style="color: gray">if </span>(sections.AfterAll != <span style="color: gray">null</span>)
        sections.AfterAll(enumerable);
    }
  }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>The delegate ForEachSectionSetter is used by the calling method with a lambda expression. As a parameter it receives an ForeachSections object, which looks like this:</p>
<pre class="code"><span style="color: gray">public class </span><span style="color: #2b91af">ForeachSections</span>&lt;T&gt; {
  <span style="color: gray">public </span><span style="color: #2b91af">Action</span>&lt;T&gt; Each { <span style="color: gray">get</span>; <span style="color: gray">set</span>; }
  <span style="color: gray">public </span><span style="color: #2b91af">Action</span>&lt;<span style="color: #2b91af">IEnumerable</span>&lt;T&gt;&gt; BeforeAll { <span style="color: gray">get</span>; <span style="color: gray">set</span>; }
  <span style="color: gray">public </span><span style="color: #2b91af">Action</span>&lt;T&gt; Before { <span style="color: gray">get</span>; <span style="color: gray">set</span>; }
  <span style="color: gray">public </span><span style="color: #2b91af">Action</span>&lt;T,T&gt; Between { <span style="color: gray">get</span>; <span style="color: gray">set</span>; }
  <span style="color: gray">public </span><span style="color: #2b91af">Action</span>&lt;T&gt; Odd { <span style="color: gray">get</span>; <span style="color: gray">set</span>; }
  <span style="color: gray">public </span><span style="color: #2b91af">Action</span>&lt;T&gt; Even { <span style="color: gray">get</span>; <span style="color: gray">set</span>; }
  <span style="color: gray">public </span><span style="color: #2b91af">Action</span>&lt;T&gt; After { <span style="color: gray">get</span>; <span style="color: gray">set</span>; }
  <span style="color: gray">public </span><span style="color: #2b91af">Action</span>&lt;<span style="color: #2b91af">IEnumerable</span>&lt;T&gt;&gt; AfterAll { <span style="color: gray">get</span>; <span style="color: gray">set</span>; }
  <span style="color: gray">public </span><span style="color: #2b91af">Action</span>&lt;<span style="color: #2b91af">IEnumerable</span>&lt;T&gt;&gt; NoData { <span style="color: gray">get</span>; <span style="color: gray">set</span>; }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>The calling method gets the chance to set the properties of this class before it is returned to the constructor of the ForEach method for processing. And because each property is already preset to a default value (Null in this case), the constructor can use the ForeachSections object just like a set of default or optional parameters. The caller can simply set values to the properties it needs, and ignore the rest.</p>
<p>If I had tried this another way, using overloadable constructors, it would have led to multiple constructors with indistinguishable signatures. If I&#8217;d have used property initializers, I wouldn&#8217;t have been able to run the whole routine without requiring a second call to the object, which actually wasn&#8217;t possible. </p>
<p>Basically, I couldn&#8217;t think of another way to do it. </p>
<p>The properties of the ForeachSections object are all delegates too. That means that we can use them with lambdas, which gives us lambdas inside of a lambda. (Hmm, very confusing!)</p>
<p>So what do you think? Could <em>you</em> use something like this? Can you make it simpler? Leave me a comment if you can.</p>

<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.richardbushnell.net%2F2008%2F06%2F02%2Fc-acrobatics-lambdas-and-expression-methods-as-a-replacement-for-nvelocity%2F&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="false" style="border:none; overflow:; width:450px; height:30px"></iframe>
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
]]></content:encoded>
			<wfw:commentRss>http://www.richardbushnell.net/2008/06/02/c-acrobatics-lambdas-and-expression-methods-as-a-replacement-for-nvelocity/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Design Guidelines for LINQ</title>
		<link>http://www.richardbushnell.net/2008/03/13/design-guidelines-for-linq/</link>
		<comments>http://www.richardbushnell.net/2008/03/13/design-guidelines-for-linq/#comments</comments>
		<pubDate>Thu, 13 Mar 2008 18:40:24 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[C# 3.0]]></category>
		<category><![CDATA[Design]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Extension Methods]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[Guidelines]]></category>

		<guid isPermaLink="false">http://richardbushnell.net/index.php/2008/03/13/design-guidelines-for-linq/</guid>
		<description><![CDATA[Have you wondered if and when you should use the new LINQ features in .Net 3.5? Like, where should I put a new extension method? Should I use Func&#60;T&#62; or a custom delegate? How do I best implement a mix-in (extension methods on an interface)? Well, Mircea Trofin has just published a new draft of [...]]]></description>
			<content:encoded><![CDATA[
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.richardbushnell.net%2F2008%2F03%2F13%2Fdesign-guidelines-for-linq%2F&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="false" style="border:none; overflow:; width:450px; height:30px"></iframe>
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<br><p>Have you wondered if and when you should use the new LINQ features in .Net 3.5?</p>
<p>Like, where should I put a new extension method? Should I use Func&lt;T&gt; or a custom delegate? How do I best implement a mix-in (extension methods on an interface)?</p>
<p>Well, Mircea Trofin has just published a new draft of some <a href="http://blogs.msdn.com/mirceat/archive/2008/03/13/linq-framework-design-guidelines.aspx" target="_blank">LINQ design guidelines</a>. You might just find your answers there.</p>

<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.richardbushnell.net%2F2008%2F03%2F13%2Fdesign-guidelines-for-linq%2F&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="false" style="border:none; overflow:; width:450px; height:30px"></iframe>
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
]]></content:encoded>
			<wfw:commentRss>http://www.richardbushnell.net/2008/03/13/design-guidelines-for-linq/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Can You Pass an Anonymous Type Across Functions?</title>
		<link>http://www.richardbushnell.net/2008/01/08/can-you-pass-an-anonymous-type-across-functions/</link>
		<comments>http://www.richardbushnell.net/2008/01/08/can-you-pass-an-anonymous-type-across-functions/#comments</comments>
		<pubDate>Tue, 08 Jan 2008 09:22:18 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Anonymous Types]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[C# 3.0]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Extension Methods]]></category>
		<category><![CDATA[Refactoring]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[passing anonymous types functions]]></category>

		<guid isPermaLink="false">http://richardbushnell.net/index.php/2008/01/08/can-you-pass-an-anonymous-type-across-functions/</guid>
		<description><![CDATA[One of the biggest questions with Anonymous Types is &#8220;can I pass them around?&#8221; If not, why not? Can you do something like this, for example: var GetAnonymousValue() { return new { Name = "Richard Bushnell" }; } void Main() { var value = GetAnonymousValue(); var name = value.Name;} The answer is simple: no, you [...]]]></description>
			<content:encoded><![CDATA[
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.richardbushnell.net%2F2008%2F01%2F08%2Fcan-you-pass-an-anonymous-type-across-functions%2F&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="false" style="border:none; overflow:; width:450px; height:30px"></iframe>
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<br><p>One of the biggest questions with Anonymous Types is &#8220;can I pass them around?&#8221; If not, why not? Can you do something like this, for example:</p>
<pre class="code"><font color="#0000ff">var</font> GetAnonymousValue() {
  <span style="color: blue">return new </span>{ Name = <span style="color: #a31515">"Richard Bushnell" </span>};
}

<span style="color: blue">void </span>Main() {
  <span style="color: blue">var </span>value = GetAnonymousValue();
  <span style="color: blue">var </span>name = value.Name;}</pre>
<p>The answer is simple: no, you can&#8217;t pass anonymous types across functions. var is not a dynamic variable, like in JavaScript. The CLR knows nothing about &#8220;var&#8221;, as the compiler just uses it to infer types when a variable is initialized.</p>
<p>At least, that was the answer until now. Using a simple extension method and generics, <a href="http://blogs.msdn.com/alexj/archive/2007/11/22/t-castbyexample-t-object-o-t-example.aspx" target="_blank">Alex James</a> just showed a nice way to pass them around on <a href="http://blogs.msdn.com/alexj/archive/2007/11/22/t-castbyexample-t-object-o-t-example.aspx" target="_blank">his blog</a>.</p>
<p>The trick is to use an example of the anonymous type you expect.</p>
<pre class="code"><span style="color: blue">object </span>GetAnonymousValue() {
  <span style="color: blue">return new </span>{ Name = <span style="color: #a31515">"Richard Bushnell" </span>};
}

<span style="color: blue">void </span>Main() {
  <span style="color: blue">var </span>value = GetAnonymousValue().CastByExample(<span style="color: blue">new </span>{ Name = <span style="color: #a31515">"" </span>});
  <span style="color: blue">var </span>name = value.Name;
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>While this might be a little dangerous, especially if you&#8217;re not testing your code regularly, this could be the solution to a few problems I can already think of. </p>
<p>Watch out for casting exceptions at runtime though! If you make a mistake anywhere, you&#8217;ll won&#8217;t get a compile-time exception, but a nasty runtime exception instead.</p>

<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.richardbushnell.net%2F2008%2F01%2F08%2Fcan-you-pass-an-anonymous-type-across-functions%2F&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="false" style="border:none; overflow:; width:450px; height:30px"></iframe>
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
]]></content:encoded>
			<wfw:commentRss>http://www.richardbushnell.net/2008/01/08/can-you-pass-an-anonymous-type-across-functions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Fun with C# Extension Methods: Quick Loops</title>
		<link>http://www.richardbushnell.net/2008/01/02/fun-with-c-sharp-extension-methods-quick-loops/</link>
		<comments>http://www.richardbushnell.net/2008/01/02/fun-with-c-sharp-extension-methods-quick-loops/#comments</comments>
		<pubDate>Tue, 01 Jan 2008 23:00:21 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[C# 3.0]]></category>
		<category><![CDATA[Extension Methods]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[C# 3.0 extension methods ruby syntax]]></category>

		<guid isPermaLink="false">http://richardbushnell.net/index.php/2008/01/02/fun-with-c-sharp-extension-methods-quick-loops/</guid>
		<description><![CDATA[In my last post, I demonstrated an extension method for easy creation of ranges, using the 1.To(x) syntax, similar to the Ruby [1..x] syntax. Today I&#8217;m writing another copy of a Ruby idea which lets you do a quick loop using a terse and easy-to-read syntax. Remember, if you want to create your own extension [...]]]></description>
			<content:encoded><![CDATA[
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.richardbushnell.net%2F2008%2F01%2F02%2Ffun-with-c-sharp-extension-methods-quick-loops%2F&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="false" style="border:none; overflow:; width:450px; height:30px"></iframe>
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<br><p>In my last post, I demonstrated an extension method for easy creation of ranges, using the 1.To(x) syntax, similar to the Ruby [1..x] syntax. Today I&#8217;m writing another copy of a Ruby idea which lets you do a quick loop using a terse and easy-to-read syntax. </p>
<p>Remember, if you want to create your own extension methods, you need to define a static class to put them in, like this:</p>
<pre class="code"><span style="color: blue">public static class </span><span style="color: #2b91af">Extensions</span></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<h2>Quick Loops</h2>
<p>Rails is king of easy loops. You can write this:</p>
<p>&nbsp; 3.times do { // block of statements }</p>
<p>Why not do the same in C# 3.0? It&#8217;s easy. Add this to your extensions class:</p>
<pre class="code"><span style="color: blue">public static void </span>Times(<span style="color: blue">this int </span>repeatCount, <span style="color: #2b91af">Action</span>&lt;<span style="color: blue">int</span>&gt; action)
{
  <span style="color: blue">for </span>(<span style="color: blue">int </span>i = 1; i &lt;= repeatCount; i++)
  {
    action(i);
  }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Now you can use this syntax in your program:</p>
<pre class="code">100.Times(t =&gt;
{
  <span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">"t:{0}"</span>, t);
});</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>t references the current counter position from 0 to the specified number.</p>
<p><strong>Question</strong>: Which would be clearer to <em>you</em> if you were taking over someone else&#8217;s code &#8211; the <em>for loop</em> in the extension method, or the .<em>Times</em> syntax? </p>
<p>It might be unfamiliar to me at first, but once I&#8217;d gotten the hang of it, I would find the extension method syntax to be much easier to follow in most situations. </p>
<p>&#8220;Hey, Richard&#8221;, I hear you shout. &#8220;What if a variable were used, such as the number of rows? Would it still be clear?&#8221; Hmm, maybe not, methinks.</p>
<p>A quick example:</p>
<pre class="code">table1.Rows.Count.Times(t =&gt;
{
  <span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">"t:{0}, name:{1}"</span>, t, table1.Rows[t]["Name"]);
});</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>With bad variable naming, this could get unwieldy. But with good naming it still looks okay:</p>
<pre class="code"><span style="color: blue">var </span>noOfRows = table.Rows.Count;
noOfRows.Times(rowNo =&gt;
{
  <span style="color: blue">var </span>row = table.Rows[rowNo];
  <span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">"rowNo:{0}, Name:{1}"</span>, rowNo, row[<span style="color: #a31515">"Name"</span>]);
});</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>This would be opposed to the more usual:</p>
<pre class="code"><span style="color: blue">for </span>(<span style="color: blue">int </span>rowNo = 0; rowNo &lt; table.Rows.Count; rowNo++)
{
  <span style="color: blue">var </span>row = table.Rows[rowNo];
  <span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">"rowNo:{0}, Name:{1}"</span>, rowNo, row[<span style="color: #a31515">"Name"</span>]);
}</pre>
<p><a href="http://11011.net/software/vspaste"></a>or even:</p>
<pre class="code"><span style="color: blue">foreach </span>(<span style="color: #2b91af">DataRow </span>row <span style="color: blue">in </span>table.Rows)
{
  <span style="color: blue">var </span>rowNo = row.Table.Rows.IndexOf(row);
  <span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">"rowNo:{0}, Name:{1}"</span>, rowNo, row[<span style="color: #a31515">"Name"</span>]);
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Despite the long syntax of the for loop, and the backwards somersaults you need to do to get the row index in the for loop, with the Times syntax you still have to use a lamda expression, and mustn&#8217;t forget the semicolon at the end of the lamda expression block. With the usual loops you don&#8217;t. As with all things, you wouldn&#8217;t always use this syntax, but sometimes it would be a good alternative.</p>
<h2>What&#8217;s next?</h2>
<p>Ruby is full of neat little tricks like I&#8217;ve presented here, and personally, I love &#8216;em. I&#8217;ll write some more soon, including &#8220;inject&#8221;, &#8220;collect&#8221; and &#8220;each&#8221;.</p>

<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.richardbushnell.net%2F2008%2F01%2F02%2Ffun-with-c-sharp-extension-methods-quick-loops%2F&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="false" style="border:none; overflow:; width:450px; height:30px"></iframe>
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
]]></content:encoded>
			<wfw:commentRss>http://www.richardbushnell.net/2008/01/02/fun-with-c-sharp-extension-methods-quick-loops/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Fun with C# Extension Methods: Easy Ranges</title>
		<link>http://www.richardbushnell.net/2007/12/31/fun-with-c-sharp-extension-methods-easy-ranges/</link>
		<comments>http://www.richardbushnell.net/2007/12/31/fun-with-c-sharp-extension-methods-easy-ranges/#comments</comments>
		<pubDate>Sun, 30 Dec 2007 22:00:07 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[C# 3.0]]></category>
		<category><![CDATA[Extension Methods]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[C# 3.0 extension methods ruby syntax ranges]]></category>

		<guid isPermaLink="false">http://richardbushnell.net/index.php/2007/12/31/fun-with-c-sharp-extension-methods-easy-ranges/</guid>
		<description><![CDATA[I&#8217;m not a real Ruby on Rails developer, but I&#8217;ve tried to learn it, just to broaden my perspective. Coming from a C# background, I&#8217;m impressed by how easy it is to read Ruby code. In fact, it is usually so compact and self-descriptive, you can understand it just by reading the code. Imagine not [...]]]></description>
			<content:encoded><![CDATA[
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.richardbushnell.net%2F2007%2F12%2F31%2Ffun-with-c-sharp-extension-methods-easy-ranges%2F&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="false" style="border:none; overflow:; width:450px; height:30px"></iframe>
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<br><p>I&#8217;m not a real Ruby on Rails developer, but I&#8217;ve tried to learn it, just to broaden my perspective. Coming from a C# background, I&#8217;m impressed by how easy it is to read Ruby code. In fact, it is usually so compact and self-descriptive, you can understand it just by reading the code. Imagine not having to write comments because your code is so clear! That&#8217;s what you can do with Ruby.</p>
<p>And now, using extension methods, it&#8217;s almost as easy to write C# code which is just as self-descriptive as Ruby code. I&#8217;m going to try to demonstrate that in this post.</p>
<h2></h2>
<p>Before we start, if you want to create your own extension methods, you need to define a static class to put them in:</p>
<pre class="code"><span style="color: blue">public static class </span><span style="color: #2b91af">Extensions</span></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>I generally make my extension methods public, because I intend them to be usable for all my projects. I&#8217;m putting them all in a common project which I reference in most of my work.</p>
<h2></h2>
<h2>Easy Ranges</h2>
<p>.Net 3.5 includes a new extension method for IEnumerable&lt;int&gt; called Range. Its first parameter is the starting integer, and its second is the number of integers to count. So to get a range from 1 to 10, you write:</p>
<pre class="code"><span style="color: #2b91af">Enumerable</span>.Range(1, 11)</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>It might be just me, but personally, I find that syntax a bit counter-intuitive. If I want the range 100 to 200, I&#8217;d have to write:</p>
<pre class="code"><span style="color: #2b91af">Enumerable</span>.Range(100, 101);</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Could I read that later, and easily understand what was being done? Not without a comment or two. When I read that code, it&#8217;s not obvious at all what range is being used.</p>
<p>But, let&#8217;s not complain. It&#8217;s easy to implement our own interpretation and extend an integer with a new method. Let&#8217;s make it more Ruby-like.</p>
<p>In Ruby you declare a range from 1 to 10 like this: [1..10]. A range of 100 to 200 looks like this: [100..200]. That&#8217;s nice, but pretty much impossible for us to define for C#. I think it would be just as good though if I could write something like this in my programs:</p>
<p><span style="color: #2b91af">IEnumerable</span>&lt;<span style="color: blue">int</span>&gt; range = 1.To(3);</p>
<p>For me, that compares quite nicely to the Ruby syntax. Plus, I get intellisense for the method on an integer, so it works well.</p>
<p>To implement that, I just have to define a new extension method like so:</p>
<pre class="code"><span style="color: blue">public static </span><span style="color: #2b91af">IEnumerable</span>&lt;<span style="color: blue">int</span>&gt; To(<span style="color: blue">this int </span>first, <span style="color: blue">int </span>last)
{
  <span style="color: blue">return </span><span style="color: #2b91af">Enumerable</span>.Range(first, last - first + 1);
}</pre>
<p>Using this new method and the new C# LINQ syntax, I could select all even numbers from 1000 to 2000 like this:</p>
<pre class="code"><span style="color: blue">var </span>odds = <span style="color: blue">from </span>i <span style="color: blue">in </span>1000.To(2000)
           <span style="color: blue">where </span>i % 2 == 0
           <span style="color: blue">select </span>i;

<span style="color: blue">foreach </span>(<span style="color: blue">var </span>i <span style="color: blue">in </span>odds)
  <span style="color: #2b91af">Console</span>.WriteLine(i);</pre>
<p>This gives 501 items, as you&#8217;d expect.</p>
<h2>What&#8217;s next?</h2>
<p>Ruby has a nice little syntax for defining a quick loop. Rails uses it a lot. I&#8217;m going to demonstrate how to create the same syntax in C# in my next post.</p>

<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.richardbushnell.net%2F2007%2F12%2F31%2Ffun-with-c-sharp-extension-methods-easy-ranges%2F&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="false" style="border:none; overflow:; width:450px; height:30px"></iframe>
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
]]></content:encoded>
			<wfw:commentRss>http://www.richardbushnell.net/2007/12/31/fun-with-c-sharp-extension-methods-easy-ranges/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>A Mixin for IComparable&lt;T&gt;</title>
		<link>http://www.richardbushnell.net/2007/12/27/a-mixin-for-icomparablet/</link>
		<comments>http://www.richardbushnell.net/2007/12/27/a-mixin-for-icomparablet/#comments</comments>
		<pubDate>Thu, 27 Dec 2007 08:03:15 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[C# 3.0]]></category>
		<category><![CDATA[Extension Methods]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[C# mixins Ruby extension methods multiple inheritance]]></category>

		<guid isPermaLink="false">http://richardbushnell.net/index.php/2007/12/27/a-mixin-for-icomparablet/</guid>
		<description><![CDATA[Following on from my other posts on C# Mixins, here&#8217;s a short one to demonstrate the benefits of Mixins using IComparable&#60;T&#62;. I don&#8217;t know about you, but I can never remember how the CompareTo method of IComparable&#60;T&#62; works. If I remember correctly, it gives back -1 if the value of the compared object is less [...]]]></description>
			<content:encoded><![CDATA[
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.richardbushnell.net%2F2007%2F12%2F27%2Fa-mixin-for-icomparablet%2F&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="false" style="border:none; overflow:; width:450px; height:30px"></iframe>
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<br><p>Following on from my other posts on C# Mixins, here&#8217;s a short one to demonstrate the benefits of Mixins using IComparable&lt;T&gt;.</p>
<p>I don&#8217;t know about you, but I can never remember how the CompareTo method of IComparable&lt;T&gt; works. If I remember correctly, it gives back -1 if the value of the compared object is less than the value of the called object, and +1 if the compared object is greater than the value of the called object.</p>
<p>No, wait! That&#8217;s the wrong way round! See what I mean? </p>
<p>The CompareTo method is defined like this:</p>
<pre class="code"><span style="color: blue">int </span>CompareTo(T other)</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>According to the MSDN Library, the value it returns is:</p>
<table cellspacing="0" cellpadding="2" width="409" border="0">
<tbody>
<tr>
<td valign="top" width="149"><strong>Value</strong></td>
<td valign="top" width="258"><strong>Meaning</strong></td>
</tr>
<tr>
<td valign="top" width="150">Less than zero</td>
<td valign="top" width="258">This object is less than the <em>other</em> parameter.</td>
</tr>
<tr>
<td valign="top" width="151">Zero</td>
<td valign="top" width="258">This object is equal to <em>other</em>.</td>
</tr>
<tr>
<td valign="top" width="151">Greater than zero</td>
<td valign="top" width="258">This object is greater than <em>other</em>.</td>
</tr>
</tbody>
</table>
<p>Now I don&#8217;t know about you, but I always have trouble with that. Mix-ins to the rescue!</p>
<p>What I really need is to define my own methods on the IComparable&lt;T&gt; interface. Something like LessThan, MoreThan and ValueEquals. That would be much more valuable. I <em>could</em> define those methods in a superclass, and have my new classes all inherit from that superclass. But that would bind me to a certain structure, reduce the coherency of my classes, and make me feel bad. But if I implement IComparable&lt;T&gt; with its sole method, I can use a Mixin to take advantage of that method and add the new functionality I need, without affecting the structure of my code.</p>
<p>Here&#8217;s an example using the Temperature class shamelessly lifted from the MSDN Library.</p>
<p>The class Temperature is defined as:</p>
<pre class="code"><span style="color: blue">public class </span><span style="color: #2b91af">Temperature </span>: <span style="color: #2b91af">IComparable</span>&lt;<span style="color: #2b91af">Temperature</span>&gt;
{
  <span style="color: green">// Implement the CompareTo method. For the parameter type, Use
  // the type specified for the type parameter of the generic
  // IComparable interface.
  //
  </span><span style="color: blue">public int </span>CompareTo(<span style="color: #2b91af">Temperature </span>other)
  {
    <span style="color: green">// The temperature comparison depends on the comparison of the
    // the underlying Double values. Because the CompareTo method is
    // strongly typed, it is not necessary to test for the correct
    // object type.
    </span><span style="color: blue">return </span>m_value.CompareTo(other.m_value);
  }

  <span style="color: green">// The underlying temperature value.
  </span><span style="color: blue">protected double </span>m_value = 0.0;

  <span style="color: blue">public </span>Temperature(<span style="color: blue">double </span>degreesKelvin)
  {
    <span style="color: blue">this</span>.Kelvin = degreesKelvin;
  }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Note that Temperature implements <span style="color: #2b91af">IComparable</span>&lt;<span style="color: #2b91af">Temperature</span>&gt;. </p>
<p>So now if you define a static extension class for IComparable&lt;T&gt;, you should also be able to use it with IComparable&lt;Temperature&gt;.</p>
<p>Here are the extension methods I&#8217;m going to add &#8211; LessThan, MoreThan, and ValueEquals:</p>
<pre class="code"><span style="color: blue">public static class </span><span style="color: #2b91af">IComparableExtensions
</span>{
  <span style="color: blue">public static bool </span>LessThan&lt;T&gt;(<span style="color: blue">this </span><span style="color: #2b91af">IComparable</span>&lt;T&gt; comparable, T other)
  {
    <span style="color: blue">return </span>comparable.CompareTo(other) &lt; 0;
  }

  <span style="color: blue">public static bool </span>MoreThan&lt;T&gt;(<span style="color: blue">this </span><span style="color: #2b91af">IComparable</span>&lt;T&gt; comparable, T other)
  {
    <span style="color: blue">return </span>comparable.CompareTo(other) &gt; 0;
  }

  <span style="color: blue">public static bool </span>ValueEquals&lt;T&gt;(<span style="color: blue">this </span><span style="color: #2b91af">IComparable</span>&lt;T&gt; comparable, T other)
  {
    <span style="color: blue">return </span>comparable.CompareTo(other) == 0;
  }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>My program now references the IComparableExtensions class by importing its namespace. I then write:</p>
<pre class="code"><span style="color: blue">var </span>t1 = <span style="color: blue">new </span><span style="color: #2b91af">Temperature</span>(273);
<span style="color: blue">var </span>t2 = <span style="color: blue">new </span><span style="color: #2b91af">Temperature</span>(100);</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>All I had to do was implement IComparable&lt;T&gt; with its one CompareTo method (which was trivial), and I automatically get the extension methods LessThan, MoreThan and ValueEquals mixed-in to my Temperature class. </p>
<pre class="code"><span style="color: blue">if </span>(t1.LessThan(t2))
  <span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">"t1 is less than t2"</span>);
<span style="color: blue">else if </span>(t1.MoreThan(t2))
  <span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">"t1 is more than t2"</span>);</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>And this doesn&#8217;t just work with IComparable&lt;Temperature&gt;, it works with anything which implements IComparable&lt;T&gt;. Classes implementing IComparable&lt;int&gt; would also get access to the new methods, for example.</p>
<p>Here&#8217;s the output of the code:</p>
<p><font face="Courier New">t1 is more than t2</font></p>
<p>&#8230; as you would expect.</p>
<p>And voila! That&#8217;s why mix-ins can be so useful.</p>
<p>I&#8217;ve intentionally done this example using a well-known interface, to make it easier to understand. But imagine what you could do by inheriting from a particular class of your own, defining your own interface, and then adding in more functionality using a mixin. You&#8217;ve nearly got multiple inheritance.</p>
<p>More to come on this&#8230;</p>

<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.richardbushnell.net%2F2007%2F12%2F27%2Fa-mixin-for-icomparablet%2F&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="false" style="border:none; overflow:; width:450px; height:30px"></iframe>
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
]]></content:encoded>
			<wfw:commentRss>http://www.richardbushnell.net/2007/12/27/a-mixin-for-icomparablet/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A not-so-simple Mixin with C# 3.0</title>
		<link>http://www.richardbushnell.net/2007/12/26/a-not-so-simple-mixin-with-c-30/</link>
		<comments>http://www.richardbushnell.net/2007/12/26/a-not-so-simple-mixin-with-c-30/#comments</comments>
		<pubDate>Wed, 26 Dec 2007 08:34:22 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[C# 3.0]]></category>
		<category><![CDATA[Extension Methods]]></category>
		<category><![CDATA[Refactoring]]></category>
		<category><![CDATA[Software]]></category>
		<category><![CDATA[C# mixin multiple inheritance]]></category>

		<guid isPermaLink="false">http://richardbushnell.net/index.php/2007/12/26/a-not-sp-simple-mixin-with-c-30/</guid>
		<description><![CDATA[My last post gave a simple idea of how to do a Mixin with C#. Rather than repeating what someone else has already done, if you want to see a more complex example of what can be done, check out Create Mixins with Interfaces and Extension Methods by Bill Wagner at MSDN.com.]]></description>
			<content:encoded><![CDATA[
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.richardbushnell.net%2F2007%2F12%2F26%2Fa-not-so-simple-mixin-with-c-30%2F&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="false" style="border:none; overflow:; width:450px; height:30px"></iframe>
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<br><p>My last post gave a simple idea of how to do a Mixin with C#. Rather than repeating what someone else has already done, if you want to see a more complex example of what can be done, check out <a href="http://msdn2.microsoft.com/en-us/vcsharp/bb625996.aspx" target="_blank">Create Mixins with Interfaces and Extension Methods</a> by <a href="http://srtsolutions.com/blogs/default.aspx" target="_blank">Bill Wagner</a> at <a href="http://msdn.com" target="_blank">MSDN.com</a>.</p>

<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.richardbushnell.net%2F2007%2F12%2F26%2Fa-not-so-simple-mixin-with-c-30%2F&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light" scrolling="no" frameborder="0" allowTransparency="false" style="border:none; overflow:; width:450px; height:30px"></iframe>
<!-- using Like-Button-Plugin-For-Wordpress [v4.2] | by http://www.gb-world.net -->
]]></content:encoded>
			<wfw:commentRss>http://www.richardbushnell.net/2007/12/26/a-not-so-simple-mixin-with-c-30/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

