<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="http://honestillusion.com/utility/FeedStylesheets/rss.xsl" media="screen"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:wfw="http://wellformedweb.org/CommentAPI/"><channel><title>Honest Illusion : .Net, C#</title><link>http://honestillusion.com/blogs/blog_0/archive/tags/.Net/C_2300_/default.aspx</link><description>Tags: .Net, C#</description><dc:language>en</dc:language><generator>CommunityServer 2.1 SP2 (Build: 61129.1)</generator><item><title>Lambda Expressions as Properties</title><link>http://honestillusion.com/blogs/blog_0/archive/2010/06/07/lambda-expressions-as-properties.aspx</link><pubDate>Mon, 07 Jun 2010 23:05:35 GMT</pubDate><guid isPermaLink="false">0c240a87-1bdc-4d60-96f7-7d0531c1460e:7946</guid><dc:creator>James</dc:creator><slash:comments>5</slash:comments><comments>http://honestillusion.com/blogs/blog_0/comments/7946.aspx</comments><wfw:commentRss>http://honestillusion.com/blogs/blog_0/commentrss.aspx?PostID=7946</wfw:commentRss><description>
  &lt;p&gt;Peter recently caused a bit of a stir with his article “&lt;a href="http://codebetter.com/blogs/peter.van.ooijen/archive/2010/05/30/sometimes-an-enum-is-not-the-best-idea.aspx" target="_blank"&gt;Sometimes an enum is not the best idea&lt;/a&gt;”.  In it, he had a very specific problem: When an enum is passed to a method as an Object, and that method converts it to a usable value by calling ToString(), you get that enum’s name and not it’s value.  And he gave a gave very specific solution to that problem.  Peter wanted an simple ad hoc solution that he could just drop into his code.  Peter’s idea was basically a quick fix to replace a bad design with something slightly less bad.   The problem arose when readers inferred that it was intended as a far more general solution, and pointed out different, more architectural solutions.  Bickering started in the comments.&lt;/p&gt;  &lt;p&gt;I think the main problem is that Peter just want a quick fix to his existing design, and viewed a proper design as overkill for his simple needs.  However, since those simple needs were out of scope of his original purpose for the  article, he never got into specifics.  However, knowing the specifics would be key to knowing how complex the design needs to be.  This was the essence of Peter’s follow-up &lt;a href="http://codebetter.com/blogs/peter.van.ooijen/archive/2010/06/02/ask-first.aspx" target="_blank"&gt;article&lt;/a&gt; (which he posted as I was in the middle of writing this)&lt;/p&gt;  &lt;p&gt;So, let’s try looking at this problem to see if we can come up with a better design that still meets the goal of being simple.&lt;/p&gt;  &lt;p&gt;In Peter’s design, he has a Suppliers class (which he occasionally refers to as the Company class), which has several instances --- one for each supplier.  There is also an enum, PublicIds with one entry for each supplier.  PublicIds was used in two places:  In switch statements, and as a parameter in an ADO.NET statement:&lt;/p&gt;  &lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; DoWithCompany(PublicIds company)
{
    &lt;span class="kwrd"&gt;switch&lt;/span&gt; (company)
    {
      &lt;span class="kwrd"&gt;case&lt;/span&gt; PublicIds.Company1:
      &lt;span class="rem"&gt;// Do something with Company 1&lt;/span&gt;
      &lt;span class="kwrd"&gt;break&lt;/span&gt;;
      &lt;span class="kwrd"&gt;case&lt;/span&gt; PublicIds.MyCompany:
      &lt;span class="rem"&gt;// Do something with My Company  &lt;/span&gt;
      &lt;span class="kwrd"&gt;break&lt;/span&gt;;
      &lt;span class="kwrd"&gt;case&lt;/span&gt; PublicIds.ThatOtherCompany:
      &lt;span class="rem"&gt;// Do something else&lt;/span&gt;
      &lt;span class="kwrd"&gt;break&lt;/span&gt;;
    }
}&lt;/pre&gt;

&lt;p&gt;cmdExists.Parameters.AddWithValue("@idSupplier", Supplier.PublicIds.MyCompany);&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;The second use was the real motivator of Peter’s article – The first was what caused all the hoopla on the blog.&lt;/p&gt;

&lt;p&gt;Commenters proposed some general ideas, basically out of Object-Oriented Design 101 – Creating a new subclass for  each of the Suppliers, with overridden methods.  Peter fought back --- the code in the “do something” blocks is not part of Supplier, but is in other classes.  Subclasses would requiring moving non-related code to where it doesn’t belong.&lt;/p&gt;

&lt;p&gt;Since Peter still hasn’t provided any real-world examples of his problem (which is reasonable, as they might involve proprietary material or just have too many dependencies to post meaningful excerpts), lets try to imagine some scenarios that might fit his description (namely that DoWithCompany is an example of  a method that “is a member of several quite different other classes and comes in many flavors”).&lt;/p&gt;

&lt;p&gt;Ok, so let’s say we have a Order class, with a ProcessOrderToSupplier(Supplier sup) method.   Let’s further say that most of Order processing is the same for all suppliers, but some suppliers offer a discount (or surcharge) under some conditions.  Hence we need custom processing per supplier to handle the discount, but moving order handling into the Supplier class would clearly be wrong.&lt;/p&gt;

&lt;p&gt;So, let’s try three different discounting schemes, and come up with three means of handling them in ways that are scalable, maintainable &amp;amp; understandable.&lt;/p&gt;

&lt;p&gt;#1 – A flat discount rate on all items.&lt;/p&gt;

&lt;p&gt;      That’s simple.  A discount rate property (getter only) in Supplier.  It could be an abstract property which is overridden in derived classes (one for each Supplier), or just set in Supplier’s constructor.  (Could be set to zero for those suppliers not offering a discount).&lt;/p&gt;

&lt;p&gt;#2 -  Several suppliers offering (free shipping on orders over $100).&lt;/p&gt;

&lt;p&gt;       The “free shipping blah-blah-blah” part is handled entirely in the Order class.  The Supplier class just needs a way to say whether of not a particular supplier offers it.  This could be handled by a  Property as described above, or an attribute on the derived class, or by a marker interface (a marker interface has no members, and is just used in statements like:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;if&lt;/span&gt; (sup &lt;span class="kwrd"&gt;is&lt;/span&gt; IOffersFreeShipping)
     ProcessFreeShipping();&lt;/pre&gt;

&lt;p&gt;#3 – One supplier offers 10% off total orders over $100. Another offers 15% off individual items over $25. And a third offers a $1 shipping surcharge on items over 20 lb.&lt;/p&gt;

&lt;p&gt;      Basically,  every supplier offers something different, and each is complex.  We’d think we’d need derived classes with overridden methods here to keep this object-oriented.  But that is exactly “the first step to multiple inheritance or an unmaintainable set of interfaces” which Peter was afraid of.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;(My laptop has an interesting way of telling me that I haven’t saved in a while --- the battery falls out.  I’ve now – too late -- discovered Windows Live Writer’s auto-save feature.  Now let’s see if I can recreate what I just lost……).&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;And besides that, creating a subclass specifically for one instance of a class just feels wrong --- particularly when we would be creating multiple subclass, one for each of several instances.  But how can be package instances of distinct functionality in individual instances of an object.&lt;/p&gt;

&lt;p&gt;By using &lt;strong&gt;Lambda Expressions as Properties.  &lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The idea is pretty simple.  We define a property, which, instead of returning some scalar value, returns a lambda expression (or pretty much any form on anonymous function).  The property works just like a instance method, except we can assign and change it at run-time.   If you’ve done any work in JavaScript, you’ve probably seen very much the same thing. &lt;/p&gt;

&lt;p&gt;Let’s look at some code.  We start by defining the Supplier class like this:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; Supplier 
{
    &lt;span class="kwrd"&gt;public&lt;/span&gt; PublicIds Id {get; &lt;span class="kwrd"&gt;private&lt;/span&gt; set;}
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;int&lt;/span&gt; IdCode {get { &lt;span class="kwrd"&gt;return&lt;/span&gt; (&lt;span class="kwrd"&gt;int&lt;/span&gt;) Id;}}
    &lt;span class="kwrd"&gt;public&lt;/span&gt; Action&amp;lt;OrderItem&amp;gt; PerItem {get; &lt;span class="kwrd"&gt;private&lt;/span&gt; set;}
    
    &lt;span class="kwrd"&gt;public&lt;/span&gt; Supplier(PublicIds id, Action&amp;lt;OrderItem&amp;gt; perItem)
    {
        Id = id;
        PerItem = perItem;
    }
    
    &lt;span class="kwrd"&gt;public&lt;/span&gt; Supplier(PublicIds id) : &lt;span class="kwrd"&gt;this&lt;/span&gt;(id, oi=&amp;gt; oi=oi)
    {}
}&lt;/pre&gt;

&lt;p&gt;Note that the constructor takes a Action delegate, and stores it in the PerItem property.&lt;/p&gt;

&lt;p&gt;Next, define our instances like this:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;Supplier Company1 = &lt;span class="kwrd"&gt;new&lt;/span&gt; Supplier(PublicIds.Company1);
Supplier MyCompany = &lt;span class="kwrd"&gt;new&lt;/span&gt; Supplier(PublicIds.MyCompany, oi=&amp;gt; { &lt;span class="kwrd"&gt;if&lt;/span&gt; (oi.Price &amp;gt; 25m) oi.Discount = oi.Price * 0.15m;});
Supplier ThatOtherCompany = &lt;span class="kwrd"&gt;new&lt;/span&gt; Supplier(PublicIds.ThatOtherCompany, oi=&amp;gt; {&lt;span class="kwrd"&gt;if&lt;/span&gt; (oi.Weight &amp;gt;=20) oi.Shipping = 1m;});&lt;/pre&gt;
And used them  like this: 

&lt;br /&gt;

&lt;pre class="csharpcode"&gt;List&amp;lt;OrderItems&amp;gt; items = &lt;span class="kwrd"&gt;new&lt;/span&gt; List&amp;lt;OrderItems&amp;gt;();    
&lt;span class="kwrd"&gt;void&lt;/span&gt; ProcessOrderToSupplier(Supplier sup)
{
    &lt;span class="rem"&gt;// :&lt;/span&gt;
    items.ForEach(sup.PerItem);
    &lt;span class="rem"&gt;//:&lt;/span&gt;
}&lt;/pre&gt;

&lt;p&gt;“Ok“, you say. “We’ve got the distinct behavior without subclasses – but we still have order processing code defined outside of the Order class, and to make matters worse, it moved to the instance definition in a really messy way.”&lt;/p&gt;

&lt;p&gt;No Problem, we just go back to out (new) old friend: Lambda Expression as Properties:&lt;/p&gt;

&lt;p&gt;This time, we’ll create static properties in the Order class:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; Order
{
    List&amp;lt;OrderItem&amp;gt; items = &lt;span class="kwrd"&gt;new&lt;/span&gt; List&amp;lt;OrderItem&amp;gt;();    
    &lt;span class="kwrd"&gt;void&lt;/span&gt; ProcessOrderToSupplier(Supplier sup)
    {
        &lt;span class="rem"&gt;// :&lt;/span&gt;
        items.ForEach(sup.PerItem);
        &lt;span class="rem"&gt;//:&lt;/span&gt;
    }    
    
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt;  Action&amp;lt;OrderItem&amp;gt; Discount15on25
    {
        get
        {
            &lt;span class="kwrd"&gt;return&lt;/span&gt; oi =&amp;gt; 
                { 
                    &lt;span class="kwrd"&gt;if&lt;/span&gt; (oi.Price &amp;gt; 25m) 
                        oi.Discount = oi.Price * 0.15m;
                };
        }
    }
    
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt;  Action&amp;lt;OrderItem&amp;gt; Shipping1Over20
    {
        get
        {
            &lt;span class="kwrd"&gt;return&lt;/span&gt; oi=&amp;gt; 
                {
                    &lt;span class="kwrd"&gt;if&lt;/span&gt; (oi.Weight &amp;gt;=20) 
                        oi.Shipping = 1m;
                };
        }
    }
}&lt;/pre&gt;

&lt;p&gt;And we can now define out Supplier instances like this:&lt;/p&gt;

&lt;p&gt; &lt;/p&gt;

&lt;pre class="csharpcode"&gt;Supplier Company1 = &lt;span class="kwrd"&gt;new&lt;/span&gt; Supplier(PublicIds.Company1);
Supplier MyCompany = &lt;span class="kwrd"&gt;new&lt;/span&gt; Supplier(PublicIds.MyCompany, Order.Discount15on25);
Supplier ThatOtherCompany = &lt;span class="kwrd"&gt;new&lt;/span&gt; Supplier(PublicIds.ThatOtherCompany, Order.Shipping1Over20);&lt;/pre&gt;

&lt;p&gt;So, what have we accomplished?&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;We’ve distinct behavior amongst the different suppliers, without resorting to subclasses or switch/case blocks &lt;/li&gt;

  &lt;li&gt;We’ve all the Order processing code in the Order class. &lt;/li&gt;

  &lt;li&gt;We’ve neat &amp;amp; tidy Supplier instance definitions, which nevertheless indicates the special features of that supplier. &lt;/li&gt;

  &lt;li&gt;And we have those special features as part of the Supplier object. &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;But, wait.  You’re probably saying that those properties we’ve defined on Order are rather specific to one particular trait.  Would it be nice to be able to have one general algorithm which is customizable?  That can be done too, by just extending the general principle, which involves using a method instead of a property, but the basic idea is still the same:  instead of returning a value, we return a function:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt;  Action&amp;lt;OrderItem&amp;gt; ShippingByWeight(&lt;span class="kwrd"&gt;int&lt;/span&gt; pounds, &lt;span class="kwrd"&gt;decimal&lt;/span&gt; cost)
{
    &lt;span class="kwrd"&gt;return&lt;/span&gt; oi=&amp;gt; 
        {
            &lt;span class="kwrd"&gt;if&lt;/span&gt; (oi.Weight &amp;gt;=pounds) 
                oi.Shipping = cost;
        };
}&lt;/pre&gt;

&lt;p&gt;// :&lt;/p&gt;

&lt;p&gt;Supplier ThatOtherCompany = &lt;span class="kwrd"&gt;new&lt;/span&gt; Supplier(PublicIds.ThatOtherCompany, Order.ShippingByWeight(20,1m); &lt;/p&gt;
&lt;a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fhonestillusion.com%2fblogs%2fblog_0%2farchive%2f2010%2f06%2f07%2flambda-expressions-as-properties.aspx"&gt;&lt;img border="0" alt="kick it on DotNetKicks.com" src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fhonestillusion.com%2fblogs%2fblog_0%2farchive%2f2010%2f06%2f07%2flambda-expressions-as-properties.aspx" /&gt;&lt;/a&gt;
&lt;div class = "shareblock"&gt;&lt;strong&gt;Share this post:&lt;/strong&gt; &lt;a title="Email Lambda+Expressions+as+Properties" href = "mailto:?body=Thought you might like this: http://honestillusion.com/blogs/blog_0/archive/2010/06/07/lambda-expressions-as-properties.aspx&amp;subject=Lambda+Expressions+as+Properties"&gt;Email it!&lt;/a&gt; | &lt;a href = "http://del.icio.us/post?url=http://honestillusion.com/blogs/blog_0/archive/2010/06/07/lambda-expressions-as-properties.aspx&amp;title=Lambda+Expressions+as+Properties" title="Submit Lambda+Expressions+as+Properties to del.icio.us" &gt;bookmark it!&lt;/a&gt; | &lt;a href = "http://www.digg.com/submit?url=http://honestillusion.com/blogs/blog_0/archive/2010/06/07/lambda-expressions-as-properties.aspx&amp;phase=2" title="Submit Lambda+Expressions+as+Properties to digg.com"&gt;digg it!&lt;/a&gt; | &lt;a href = "http://reddit.com/submit?url=http://honestillusion.com/blogs/blog_0/archive/2010/06/07/lambda-expressions-as-properties.aspx&amp;title=Lambda+Expressions+as+Properties" title="Submit Lambda+Expressions+as+Properties to reddit.com"&gt;reddit!&lt;/a&gt;&lt;/div&gt;&lt;img src="http://honestillusion.com/aggbug.aspx?PostID=7946" width="1" height="1"&gt;</description><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/Code/default.aspx">Code</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/.Net/default.aspx">.Net</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/Programming/default.aspx">Programming</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/dotnet/default.aspx">dotnet</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/csharp/default.aspx">csharp</category></item><item><title>Portable Areas for Castle Monorail, Part 2</title><link>http://honestillusion.com/blogs/blog_0/archive/2010/04/01/portable-areas-for-castle-monorail-part-2.aspx</link><pubDate>Thu, 01 Apr 2010 23:15:00 GMT</pubDate><guid isPermaLink="false">0c240a87-1bdc-4d60-96f7-7d0531c1460e:7936</guid><dc:creator>James</dc:creator><slash:comments>1</slash:comments><comments>http://honestillusion.com/blogs/blog_0/comments/7936.aspx</comments><wfw:commentRss>http://honestillusion.com/blogs/blog_0/commentrss.aspx?PostID=7936</wfw:commentRss><description>
  &lt;P&gt;In our last episode, we discussed the PortableAreaController base class, which makes it simple to create a portable area using Monorail.  In this installment, we put that class to use.&lt;/P&gt;
&lt;P&gt;For the purposes of this example, the controller isn’t going to do anything useful – I’m not even going to bother with code in the actions.  The different actions will display different views so you can see the effect, and I’m hoping you’ll just trust that you can put real code in the action methods.&lt;/P&gt;&lt;PRE class="csharpcode"&gt;[Layout(&lt;SPAN class="str"&gt;"default"&lt;/SPAN&gt;,&lt;SPAN class="str"&gt;"patest"&lt;/SPAN&gt;)]
&lt;SPAN class="kwrd"&gt;public&lt;/SPAN&gt; &lt;SPAN class="kwrd"&gt;class&lt;/SPAN&gt; PATest : PortableAreaController
{
    &lt;SPAN class="kwrd"&gt;public&lt;/SPAN&gt; &lt;SPAN class="kwrd"&gt;void&lt;/SPAN&gt; Page1()
    {         }
    &lt;SPAN class="kwrd"&gt;public&lt;/SPAN&gt; &lt;SPAN class="kwrd"&gt;void&lt;/SPAN&gt; Page2()
    {         }
    &lt;SPAN class="kwrd"&gt;public&lt;/SPAN&gt; &lt;SPAN class="kwrd"&gt;void&lt;/SPAN&gt; Page3()
    {         }
}&lt;/PRE&gt;
&lt;P&gt; &lt;/P&gt;
&lt;P&gt;That’s our minimalistic example.  If it looks a lot like an ordinary Monorail controller, that’s the idea.    “PATest” is the name of the controller, which in the case of a Portable Area, is the name of the entire feature, so it’s be something like CoolWiki or MyForum.  &lt;/P&gt;
&lt;P&gt;The Action methods are identical to what you’d have in a normal controller.  In fact, everything in the portable controller is just like it would be if this were a intrinsic part of a website.  &lt;/P&gt;
&lt;P&gt;The rest is just about putting the pieces together in the assembly.   &lt;/P&gt;
&lt;P&gt;&lt;A href="http://honestillusion.com/blogs/blog_0/PortableAreaSolution_7652A1E6.png"&gt;&lt;IMG style="BORDER-RIGHT-WIDTH:0px;DISPLAY:inline;BORDER-TOP-WIDTH:0px;BORDER-BOTTOM-WIDTH:0px;BORDER-LEFT-WIDTH:0px;" title="PortableAreaSolution" border="0" alt="PortableAreaSolution" src="http://honestillusion.com/blogs/blog_0/PortableAreaSolution_thumb_6E5AFF84.png" width="244" height="226" /&gt;&lt;/A&gt; &lt;/P&gt;
&lt;P&gt;Individual files  (images, css files etc) should be placed in the root level of the project.  When referencing then in a view, just added “.rails” to the end ( &amp;lt;img src=”${siteRoot}/PATest/autolist.png.rails” /&amp;gt;)&lt;/P&gt;
&lt;P&gt;View templates should be in a folder named after the controller, and layouts in a “layouts” folder --- just as if the root level was the website’s “Views” folder.  You don;t have to do anything special to get Monorail to find them – that is handled for you by the base class.&lt;/P&gt;
&lt;P&gt;All those files (not the CS files obviously) should have their Build Action set to Embedded Resource.&lt;/P&gt;
&lt;P&gt;Note that when a view template is needed, Monorail will first look for a physical file in the website’s Views files, and failing there, search in the assembly.  This allows the end user to override the embedded view templates with their own.   In the example I’ve uploaded to the CastleContrib SVN repository, I’ve locally overridden Page2.&lt;/P&gt;
&lt;P&gt;The same holds for layouts, which I’ve put to use in the example.  I assumed that most sites will have a default layout for the site (which I further assumed is called “default”).  The controller uses that layout and adds it’s own child layout.  (The project should also define a simple default layout as just “${childContent}” just in case the website it’s being used in doesn’t define one.)&lt;/P&gt;
&lt;P&gt;The PortableAreaController base class has been added to the ViewComponent project in the CastleContrib SVN repository. (Yes, I know it’s not a ViewComponent, but I didn’t want to create a whole new branch -- particularly not for just one file-- and ViewComponents were the closest available existing project).  The PATest example shown here is a separate project under that branch, with the resulting Castle.MonoRail.PortableAreaExample.dll assembly added to the ViewComponent.TestSite project.  Note that that assembly is the &lt;EM&gt;only&lt;/EM&gt; file added to the website to enable this functionality, and the only other change was to add a reference to it into the web.config.&lt;/P&gt;
&lt;div class = "shareblock"&gt;&lt;strong&gt;Share this post:&lt;/strong&gt; &lt;a title="Email Portable+Areas+for+Castle+Monorail%2c+Part+2" href = "mailto:?body=Thought you might like this: http://honestillusion.com/blogs/blog_0/archive/2010/04/01/portable-areas-for-castle-monorail-part-2.aspx&amp;subject=Portable+Areas+for+Castle+Monorail%2c+Part+2"&gt;Email it!&lt;/a&gt; | &lt;a href = "http://del.icio.us/post?url=http://honestillusion.com/blogs/blog_0/archive/2010/04/01/portable-areas-for-castle-monorail-part-2.aspx&amp;title=Portable+Areas+for+Castle+Monorail%2c+Part+2" title="Submit Portable+Areas+for+Castle+Monorail%2c+Part+2 to del.icio.us" &gt;bookmark it!&lt;/a&gt; | &lt;a href = "http://www.digg.com/submit?url=http://honestillusion.com/blogs/blog_0/archive/2010/04/01/portable-areas-for-castle-monorail-part-2.aspx&amp;phase=2" title="Submit Portable+Areas+for+Castle+Monorail%2c+Part+2 to digg.com"&gt;digg it!&lt;/a&gt; | &lt;a href = "http://reddit.com/submit?url=http://honestillusion.com/blogs/blog_0/archive/2010/04/01/portable-areas-for-castle-monorail-part-2.aspx&amp;title=Portable+Areas+for+Castle+Monorail%2c+Part+2" title="Submit Portable+Areas+for+Castle+Monorail%2c+Part+2 to reddit.com"&gt;reddit!&lt;/a&gt;&lt;/div&gt;&lt;img src="http://honestillusion.com/aggbug.aspx?PostID=7936" width="1" height="1"&gt;</description><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/Code/default.aspx">Code</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/.Net/default.aspx">.Net</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/Programming/default.aspx">Programming</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/dotnet/default.aspx">dotnet</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/csharp/default.aspx">csharp</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/castle/default.aspx">castle</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/monorail/default.aspx">monorail</category></item><item><title>Portable Areas for Castle Monorail</title><link>http://honestillusion.com/blogs/blog_0/archive/2010/04/01/portable-areas-for-castle-monorail.aspx</link><pubDate>Thu, 01 Apr 2010 23:09:59 GMT</pubDate><guid isPermaLink="false">0c240a87-1bdc-4d60-96f7-7d0531c1460e:7935</guid><dc:creator>James</dc:creator><slash:comments>1</slash:comments><comments>http://honestillusion.com/blogs/blog_0/comments/7935.aspx</comments><wfw:commentRss>http://honestillusion.com/blogs/blog_0/commentrss.aspx?PostID=7935</wfw:commentRss><description>
  
&lt;p&gt;Recently I had read a blogger comparing Castle Monorail with ASP.NET MVC.  He chose ASP.NET mainly because it supported Portable Areas while Monorail did not.  As a supporter of Monorail, I was very offended by this, and decided to correct the problem.  The first step… finding out exactly what a “portable area” was.&lt;/p&gt;
&lt;p&gt;A Portable Area is a piece of functionality, with all pieces bundled up into a single assembly, which can be just “dropped into” an existing website.  Think of a forum or a wiki.  The idea is basically, I could just add wiki.dll to my site, and suddenly &lt;a href="http://www.mysite.com/wiki"&gt;www.mysite.com/wiki&lt;/a&gt; just works.&lt;/p&gt;
&lt;p&gt;Now, having a controller and its actions together in a single assembly is a basic design principle of Monorail (and essentially all of MVC design), so that part was done before I even began.  The rest was a bit trickier.&lt;/p&gt;
&lt;p&gt;I would have to store – and retrieve at the right times, the view template files, and all other associated files – images, style sheets, script files, etc.&lt;/p&gt;
&lt;p&gt;Storing the files was in itself trivial -- .NET has a means built right it. The file just need to be added to the project as embedded resources.  In Visual Studio, on the file’s property panel, set the “Build  Action” to “Embedded Resource”.&lt;/p&gt;
&lt;p&gt;Now that the files were in the assembly, we had to get them out of it. For views, which I had assumed were going to be the most trouble, this turned out to be simple, with the plumbing for it was already built into the Monorail framework.  Apparently, someone had planned for portable areas, but never followed through.  View templates are loaded by a class aptly called the FileAssemblyViewSourceLoader.  It looks in the “Views” folder for the template, and failing there, looks among the embedded resources of the assemblies in its collection.  However, nothing in the framework ever added an assembly to that collection, so this feature has always laid fallow.&lt;/p&gt;
&lt;p&gt;The final feature was getting it to load a random file from the resources.  Whenever I need to do something with a name not known in advance, a DefaultAction seems like the way to go.&lt;/p&gt;
&lt;p&gt;With that, all the pieces were in place, I just had a wee bit of code to tie them all together.  Defining a base class which a portable area could be derived from seemed the best approach.&lt;/p&gt;
&lt;pre class="csharpcode"&gt;
  &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; PortableAreaController : SmartDispatcherController&lt;/pre&gt;
&lt;p&gt;{&lt;/p&gt;
&lt;p&gt;The first step was to override the Initialize() method, so that I could add this assembly to the list searched by FileAssemblyViewSourceLoader.  The only trick here is we must make sure that the assembly is only added once, regardless of how many times the controller is initialized.    And, while we are at it, we’ll also get the assembly name and a list of the resources and save them for later.&lt;/p&gt;
&lt;pre class="csharpcode"&gt;
  &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt;[] resourceNames;
&lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt; asmName;

&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;override&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Initialize()
{
    &lt;span class="kwrd"&gt;base&lt;/span&gt;.Initialize();
    var asm = &lt;span class="kwrd"&gt;this&lt;/span&gt;.GetType().Assembly;
    resourceNames = asm.GetManifestResourceNames();
    asmName = asm.GetName().Name;
    var asminfo = &lt;span class="kwrd"&gt;new&lt;/span&gt; AssemblySourceInfo(asm, asmName.ToLower());
    &lt;span class="kwrd"&gt;if&lt;/span&gt; (!&lt;span class="kwrd"&gt;this&lt;/span&gt;.Context.Services.ViewSourceLoader.AssemblySources.Cast&amp;lt;AssemblySourceInfo&amp;gt;()&lt;br /&gt;                            .Any(asi=&amp;gt;asi.AssemblyName==asminfo.AssemblyName))
        &lt;span class="kwrd"&gt;this&lt;/span&gt;.Context.Services.ViewSourceLoader.AddAssemblySource(asminfo);
}&lt;/pre&gt;
&lt;p&gt;Next is the DefaultAction.  The idea here is that you request somefile.jpg.rails, and we pull somefile.jpg out of the resources, and stream it to the browser.  In Monorail, a DefaultAction is a method which is called when no other method in the controller matches the action.  In our DefaultAction, we’ll generate a resource name from the assembly name and the Action name.  The Action is basically, the name of the “file” requested without the “.rails” extension, so if we ask for file “http://mysite.com/portable/myimage.gif.rails”, then the pseudo-file we are requesting is “myimage.gif.rails” which makes the Action “myimage.gif” which just happens to be the file we really want.  The only tricky part here is the GetContentTypeFromExt() function.  The problem is that there is a very simple way to do this --- which only works under Windows.  Now, while the vast majority of web servers running Monorail are Windows based, Monorail is designed to also run under Mono (Linux).   I couldn’t find a good portable way to handle this, so I just punted (check the source for dirty secrets).&lt;/p&gt;
&lt;p&gt;[DefaultAction] 
  &lt;br /&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; DefaultAction() 

  &lt;br /&gt;{ 

  &lt;br /&gt;    &lt;span class="kwrd"&gt;string&lt;/span&gt; filename = asmName + &lt;span class="str"&gt;"."&lt;/span&gt; + Action; 

  &lt;br /&gt;    var resourceName = resourceNames.FirstOrDefault(rn=&amp;gt; rn.Equals(filename,StringComparison.InvariantCultureIgnoreCase)); 

  &lt;br /&gt;    &lt;span class="kwrd"&gt;if&lt;/span&gt; (resourceName!= &lt;span class="kwrd"&gt;null&lt;/span&gt;) 

  &lt;br /&gt;    { 

  &lt;br /&gt;        &lt;span class="kwrd"&gt;string&lt;/span&gt; ext = Path.GetExtension(filename); 

  &lt;br /&gt;        &lt;span class="kwrd"&gt;this&lt;/span&gt;.Response.ContentType = GetContentTypeFromExt(ext); 

  &lt;br /&gt;

  &lt;br /&gt;        Stream contents = &lt;span class="kwrd"&gt;this&lt;/span&gt;.GetType().Assembly.GetManifestResourceStream(resourceName); 

  &lt;br /&gt;        &lt;span class="kwrd"&gt;this&lt;/span&gt;.Response.BinaryWrite(contents); 

  &lt;br /&gt;        CancelView(); 

  &lt;br /&gt;    } 

  &lt;br /&gt;} 

  &lt;br /&gt;&lt;/p&gt;
&lt;p&gt;This method is the controller’s Default action by virtue of the [DefaultAction] attribute.  The name is arbitrary – DefaultAction just kept things simple.&lt;/p&gt;
&lt;p&gt;And with that, everything you need to write a portable area in Monorail is neatly contained in a simple base class.  Everything we’ve just gone over, you can now completely ignore.   &lt;/p&gt;
&lt;p&gt;Next, we discuss how you use this base class to write your own portable area.&lt;/p&gt;
&lt;div class = "shareblock"&gt;&lt;strong&gt;Share this post:&lt;/strong&gt; &lt;a title="Email Portable+Areas+for+Castle+Monorail" href = "mailto:?body=Thought you might like this: http://honestillusion.com/blogs/blog_0/archive/2010/04/01/portable-areas-for-castle-monorail.aspx&amp;subject=Portable+Areas+for+Castle+Monorail"&gt;Email it!&lt;/a&gt; | &lt;a href = "http://del.icio.us/post?url=http://honestillusion.com/blogs/blog_0/archive/2010/04/01/portable-areas-for-castle-monorail.aspx&amp;title=Portable+Areas+for+Castle+Monorail" title="Submit Portable+Areas+for+Castle+Monorail to del.icio.us" &gt;bookmark it!&lt;/a&gt; | &lt;a href = "http://www.digg.com/submit?url=http://honestillusion.com/blogs/blog_0/archive/2010/04/01/portable-areas-for-castle-monorail.aspx&amp;phase=2" title="Submit Portable+Areas+for+Castle+Monorail to digg.com"&gt;digg it!&lt;/a&gt; | &lt;a href = "http://reddit.com/submit?url=http://honestillusion.com/blogs/blog_0/archive/2010/04/01/portable-areas-for-castle-monorail.aspx&amp;title=Portable+Areas+for+Castle+Monorail" title="Submit Portable+Areas+for+Castle+Monorail to reddit.com"&gt;reddit!&lt;/a&gt;&lt;/div&gt;&lt;img src="http://honestillusion.com/aggbug.aspx?PostID=7935" width="1" height="1"&gt;</description><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/Code/default.aspx">Code</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/.Net/default.aspx">.Net</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/Programming/default.aspx">Programming</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/dotnet/default.aspx">dotnet</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/csharp/default.aspx">csharp</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/castle/default.aspx">castle</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/monorail/default.aspx">monorail</category></item><item><title>Some Better-Written Custom String Methods using C#</title><link>http://honestillusion.com/blogs/blog_0/archive/2010/02/02/some-better-written-custom-string-methods-using-c.aspx</link><pubDate>Wed, 03 Feb 2010 01:07:00 GMT</pubDate><guid isPermaLink="false">0c240a87-1bdc-4d60-96f7-7d0531c1460e:7914</guid><dc:creator>James</dc:creator><slash:comments>2</slash:comments><comments>http://honestillusion.com/blogs/blog_0/comments/7914.aspx</comments><wfw:commentRss>http://honestillusion.com/blogs/blog_0/commentrss.aspx?PostID=7914</wfw:commentRss><description>
  &lt;P&gt;In my daily web-surfing, I often stumble upon snippets of C# code posted by people.  Usually, I can tweak  it a bit. Sometimes, I can tweak it a lot.  I usually post a quick comment to the site offering it.  Today, I came upon some code that was so bad --- which the author said was from his forthcoming &lt;B&gt;&lt;I&gt;book! &lt;/I&gt;&lt;/B&gt;--- more drastic measures must be taken.&lt;/P&gt;
&lt;P&gt;First we have a function to put a string into “Title Case” (which the author refers to as “Proper Case”) – Having the first letter of each word capitalized.  Here’s the original:&lt;/P&gt;&lt;PRE class="csharpcode"&gt;&lt;SPAN class="kwrd"&gt;public&lt;/SPAN&gt; &lt;SPAN class="kwrd"&gt;static&lt;/SPAN&gt; String PCase(String strParam)
 {
     String strProper = strParam.Substring(0, 1).ToUpper();
     strParam = strParam.Substring(1).ToLower();
     String strPrev = &lt;SPAN class="str"&gt;""&lt;/SPAN&gt;;
     &lt;SPAN class="kwrd"&gt;for&lt;/SPAN&gt; (&lt;SPAN class="kwrd"&gt;int&lt;/SPAN&gt; iIndex = 0; iIndex &amp;lt; strParam.Length; iIndex++)
     {         
&lt;SPAN class="kwrd"&gt;         if&lt;/SPAN&gt; (iIndex &amp;gt; 1)
         {
             strPrev = strParam.Substring(iIndex - 1, 1);
         }
         &lt;SPAN class="kwrd"&gt;if&lt;/SPAN&gt; (strPrev.Equals(&lt;SPAN class="str"&gt;" "&lt;/SPAN&gt;) ||
         strPrev.Equals(&lt;SPAN class="str"&gt;"\t"&lt;/SPAN&gt;) ||
         strPrev.Equals(&lt;SPAN class="str"&gt;"\n"&lt;/SPAN&gt;) ||
         strPrev.Equals(&lt;SPAN class="str"&gt;"."&lt;/SPAN&gt;))
         {
             strProper += strParam.Substring(iIndex, 1).ToUpper();
         }
         &lt;SPAN class="kwrd"&gt;else&lt;/SPAN&gt;
         {
             strProper += strParam.Substring(iIndex, 1);
         }
     }
     &lt;SPAN class="kwrd"&gt;return&lt;/SPAN&gt; strProper;
 } &lt;/PRE&gt;
&lt;P&gt;What wrong here?  Lot’s of really bad string handling.  Remember, strings are immutable, so any action on one creates a new string.  So, “strParam.Substring(iIndex, 1)” creates a new string. “strParam.Substring(iIndex, 1).ToUpper()” create two new strings, and “strProper += strParam.Substring(iIndex, 1).ToUpper();” creates three new strings.  And, that’s within a loop.   And, since Substring is always used here to create a one-character string, it easier to just use a char --- except apparently, this book author doesn’t know how to.   Nor, doesn’t he apparently know about StringBuilder.  Then, we get to the algorithm itself, where he does such bizarre things as pointlessly treat the first character as a special case, in two different places. &lt;/P&gt;
&lt;P&gt;Ok, now let’s see the revision:&lt;/P&gt;&lt;PRE class="csharpcode"&gt;    &lt;SPAN class="kwrd"&gt;public&lt;/SPAN&gt; &lt;SPAN class="kwrd"&gt;static&lt;/SPAN&gt; String PCase(String strParam)
{
         StringBuilder sb = &lt;SPAN class="kwrd"&gt;new&lt;/SPAN&gt; StringBuilder(strParam.Length);
         &lt;SPAN class="kwrd"&gt;char&lt;/SPAN&gt; cPrev = &lt;SPAN class="str"&gt;'.'&lt;/SPAN&gt;;  &lt;SPAN class="rem"&gt;// start with something to force the next character to upper.&lt;/SPAN&gt;
        &lt;SPAN class="kwrd"&gt;foreach&lt;/SPAN&gt;(&lt;SPAN class="kwrd"&gt;char&lt;/SPAN&gt; c &lt;SPAN class="kwrd"&gt;in&lt;/SPAN&gt; strParam)
         {
             &lt;SPAN class="kwrd"&gt;if&lt;/SPAN&gt; (cPrev == &lt;SPAN class="str"&gt;'.'&lt;/SPAN&gt; || Char.IsWhiteSpace(cPrev))
                 sb.Append(Char.ToUpper(c));
             &lt;SPAN class="kwrd"&gt;else&lt;/SPAN&gt;
                 sb.Append(Char.ToLower(c));
             cPrev = c;
         }
         &lt;SPAN class="kwrd"&gt;return&lt;/SPAN&gt; sb.ToString();
     }  &lt;/PRE&gt;
&lt;P&gt;&lt;BR /&gt;First we start with a string builder, preallocated to the size of the string we are building.  The method doesn’t change the length of the string, so we know the length of the final string right from the start.&lt;/P&gt;
&lt;P&gt;Next, since we are going to capitalize every letter after a period, and also the first letter, why not just pretend the mythical initial “last” character was a period?  Suddenly, the first letter is no longer a special case, and we still get what we want.&lt;/P&gt;
&lt;P&gt;Then, we just loop through the letters, raising or lowering letter as we need. Note that it works on characters and not strings, and uses the build-in IsWhitespace method, instead of using a  hardcoded list of a subset of them.  A for() loop can in certain cases (however, not the one used in the original) be faster than a foreach(), but here I figured it was safe to sacrifice a tiny bit of speed for clearer code.&lt;/P&gt;
&lt;P&gt;Next up, Reversing a String.  The Original:&lt;/P&gt;&lt;PRE class="csharpcode"&gt;    &lt;SPAN class="kwrd"&gt;public&lt;/SPAN&gt; &lt;SPAN class="kwrd"&gt;static&lt;/SPAN&gt; String Reverse(String strParam)
     {
         &lt;SPAN class="kwrd"&gt;if&lt;/SPAN&gt; (strParam.Length == 1)
         {
             &lt;SPAN class="kwrd"&gt;return&lt;/SPAN&gt; strParam;
         }
         &lt;SPAN class="kwrd"&gt;else&lt;/SPAN&gt;
         {
             &lt;SPAN class="kwrd"&gt;return&lt;/SPAN&gt; Reverse(strParam.Substring(1)) + strParam.Substring(0, 1);
         }
     }&lt;/PRE&gt;
&lt;P&gt;Now, here the author might be able to earn a pass.  It’s possible that somewhere in his book he talks about recursive functions, and uses this as an example.  Then, if might be OK.  I mean, it is the only reason I can think of that someone might want a function which reverses a string – despite ubiquity of string reversing functions in libraries like this.  But, he presented it on his blog as a collection of string functions, so we’ll have to judge them on that basis.  &lt;/P&gt;
&lt;P&gt;Again we have lots of string manipulation to accomplish something simple --- where there are already method built into the framework to handle such things:&lt;/P&gt;&lt;PRE class="csharpcode"&gt;&lt;SPAN class="kwrd"&gt;public&lt;/SPAN&gt; &lt;SPAN class="kwrd"&gt;static&lt;/SPAN&gt; String Reverse(String strParam)
{
     &lt;SPAN class="kwrd"&gt;byte&lt;/SPAN&gt;[] rev = Encoding.ASCII.GetBytes(strParam);
     Array.Reverse(rev);
     &lt;SPAN class="kwrd"&gt;return&lt;/SPAN&gt; Encoding.ASCII.GetString(rev);
}&lt;/PRE&gt;
&lt;P&gt;&lt;STRONG&gt;UPDATE:&lt;/STRONG&gt; One commentator noted (quite rightly) noted that my Reverse() method would only work for strings of ASCII characters and will fail if there are any Unicode characters.   I knew that at the time, but I was hoping no one else would notice.  The problem was I needed a method which converted a string into an array of characters, and being unable to find one in the CLR, I substituted a string to byte array method instead.   I guess this is one of those times where you just have to step away for a while and come back to it, because now, I found the right method in a few seconds:&lt;/P&gt;
&lt;P&gt; &lt;SPAN class="kwrd"&gt;public&lt;/SPAN&gt; &lt;SPAN class="kwrd"&gt;static&lt;/SPAN&gt; String Reverse(String strParam)&lt;/P&gt;
&lt;DIV class="csharpcode"&gt;&lt;PRE&gt;{&lt;/PRE&gt;&lt;PRE class="alt"&gt;     &lt;SPAN class="kwrd"&gt;char&lt;/SPAN&gt;[] rev = strParam.ToCharArray();&lt;/PRE&gt;&lt;PRE&gt;     Array.Reverse(rev);&lt;/PRE&gt;&lt;PRE class="alt"&gt;     &lt;SPAN class="kwrd"&gt;return&lt;/SPAN&gt; &lt;SPAN class="kwrd"&gt;new&lt;/SPAN&gt; String(rev);&lt;/PRE&gt;&lt;PRE&gt;}&lt;/PRE&gt;&lt;/DIV&gt;
&lt;P&gt;And while my first version was a big improvement over the original, this is a big improvement over my first version, so you get double the benefits!&lt;/P&gt;
&lt;P&gt;Next, we have a simple function to count the occurrences of a substring.  &lt;/P&gt;&lt;PRE class="csharpcode"&gt;&lt;SPAN class="kwrd"&gt;public&lt;/SPAN&gt; &lt;SPAN class="kwrd"&gt;static&lt;/SPAN&gt; &lt;SPAN class="kwrd"&gt;int&lt;/SPAN&gt; CharCount(String strSource, String strToCount)
{
    &lt;SPAN class="kwrd"&gt;int&lt;/SPAN&gt; iCount = 0;
    &lt;SPAN class="kwrd"&gt;int&lt;/SPAN&gt; iPos = strSource.IndexOf(strToCount);
    &lt;SPAN class="kwrd"&gt;while&lt;/SPAN&gt; (iPos != -1)
    {
        iCount++;
        strSource = strSource.Substring(iPos + 1);
        iPos = strSource.IndexOf(strToCount);
    }
    &lt;SPAN class="kwrd"&gt;return&lt;/SPAN&gt; iCount;}&lt;/PRE&gt;
&lt;P&gt;The revision isn’t much different but the subtle difference is important.  Instead of creating a new, shorter string to search, we tell it to just start looking after the last match.  Instead we now merely look at the string.&lt;/P&gt;&lt;PRE class="csharpcode"&gt;&lt;SPAN class="kwrd"&gt;public&lt;/SPAN&gt; &lt;SPAN class="kwrd"&gt;static&lt;/SPAN&gt; &lt;SPAN class="kwrd"&gt;int&lt;/SPAN&gt; CharCount(String strSource, String strToCount)
{
    &lt;SPAN class="kwrd"&gt;int&lt;/SPAN&gt; iCount = 0;
    &lt;SPAN class="kwrd"&gt;int&lt;/SPAN&gt; iPos = strSource.IndexOf(strToCount);
    &lt;SPAN class="kwrd"&gt;while&lt;/SPAN&gt; (iPos != -1)
    {
        iCount++;
        iPos = strSource.IndexOf(strToCount, iPos+1);
    }
    &lt;SPAN class="kwrd"&gt;return&lt;/SPAN&gt; iCount;
}&lt;/PRE&gt;The next one has a special problem --- It doesn’t do what it claims to do!&lt;BR /&gt;&lt;PRE class="csharpcode"&gt;&lt;SPAN class="rem"&gt;// Trim the string to contain only a single whitepace between words&lt;/SPAN&gt;&lt;/PRE&gt;&lt;PRE class="csharpcode"&gt;&lt;SPAN class="rem"&gt;&lt;/SPAN&gt;&lt;SPAN class="kwrd"&gt;public&lt;/SPAN&gt; &lt;SPAN class="kwrd"&gt;static&lt;/SPAN&gt; String ToSingleSpace(String strParam)
{
    &lt;SPAN class="kwrd"&gt;int&lt;/SPAN&gt; iPosition = strParam.IndexOf(&lt;SPAN class="str"&gt;" "&lt;/SPAN&gt;);
    &lt;SPAN class="kwrd"&gt;if&lt;/SPAN&gt; (iPosition == -1)
    {
        &lt;SPAN class="kwrd"&gt;return&lt;/SPAN&gt; strParam;
    }
    &lt;SPAN class="kwrd"&gt;else&lt;/SPAN&gt;
    {
        &lt;SPAN class="kwrd"&gt;return&lt;/SPAN&gt; ToSingleSpace(strParam.Substring(0, iPosition) +        strParam.Substring(iPosition + 1));
    }
}&lt;/PRE&gt;
&lt;P&gt;Now, it says that it should remove repeated space, so that there is only one space between words. However, what it actually does it to remove all spaces.  This gives us a problem: Should my rewritten function do what it claims to do, or what it actually does?  I decided to give you one of each.&lt;/P&gt;
&lt;P&gt;Duplicating the result is quite straightforward:&lt;/P&gt;&lt;PRE class="csharpcode"&gt;&lt;SPAN class="kwrd"&gt;public&lt;/SPAN&gt; &lt;SPAN class="kwrd"&gt;static&lt;/SPAN&gt; String RemoveAllSpaces(String strParam)
{
    &lt;SPAN class="kwrd"&gt;return&lt;/SPAN&gt; strParam.Replace(&lt;SPAN class="str"&gt;" "&lt;/SPAN&gt;, &lt;SPAN class="str"&gt;""&lt;/SPAN&gt;);
}&lt;/PRE&gt;
&lt;P&gt;Writing a function to do what it is supposed to is a little more involved, but still simple:&lt;/P&gt;&lt;PRE class="csharpcode"&gt;&lt;SPAN class="kwrd"&gt;public&lt;/SPAN&gt; &lt;SPAN class="kwrd"&gt;static&lt;/SPAN&gt; String ToSingleSpace(String strParam)
{
    var sb = &lt;SPAN class="kwrd"&gt;new&lt;/SPAN&gt; StringBuilder(strParam.Length);
    var prevWS =&lt;SPAN class="kwrd"&gt;true&lt;/SPAN&gt;;
    &lt;SPAN class="kwrd"&gt;foreach&lt;/SPAN&gt;(var c &lt;SPAN class="kwrd"&gt;in&lt;/SPAN&gt; strParam)
    {
        &lt;SPAN class="kwrd"&gt;if&lt;/SPAN&gt; (Char.IsWhiteSpace(c))
        {
            &lt;SPAN class="kwrd"&gt;if&lt;/SPAN&gt; (!prevWS)
                sb.Append(&lt;SPAN class="str"&gt;' '&lt;/SPAN&gt;);
            prevWS = &lt;SPAN class="kwrd"&gt;true&lt;/SPAN&gt;;
        }
        &lt;SPAN class="kwrd"&gt;else&lt;/SPAN&gt;
        {
            sb.Append(c);
            prevWS = &lt;SPAN class="kwrd"&gt;false&lt;/SPAN&gt;;
        }
    }
    &lt;SPAN class="kwrd"&gt;return&lt;/SPAN&gt; sb.ToString();
}&lt;/PRE&gt;We create a string builder the size of our source string, which would be the maximum size our trimmed string could be, and we set prevWS to true.  This way, it will remove all leading whitespace.  Then we just step through the string, character by character, appending that character to our new string if it’s not a whitespace character, and appending a space for the first whitespace character found.  Note that this reduces all forms of whitespace (tabs, newlines, spaces etc) to a single space.  The original just worked on spaces. 
&lt;P&gt;Finally, we have a function to determine is a string is a palindrome.  &lt;/P&gt;&lt;PRE class="csharpcode"&gt;&lt;SPAN class="kwrd"&gt;public&lt;/SPAN&gt; &lt;SPAN class="kwrd"&gt;static&lt;/SPAN&gt; &lt;SPAN class="kwrd"&gt;bool&lt;/SPAN&gt; IsPalindrome(String strParam)
{
    &lt;SPAN class="kwrd"&gt;int&lt;/SPAN&gt; iLength, iHalfLen;
    iLength = strParam.Length - 1;
    iHalfLen = iLength / 2;
    &lt;SPAN class="kwrd"&gt;for&lt;/SPAN&gt; (&lt;SPAN class="kwrd"&gt;int&lt;/SPAN&gt; iIndex = 0; iIndex &amp;lt;= iHalfLen; iIndex++)
    {
        &lt;SPAN class="kwrd"&gt;if&lt;/SPAN&gt; (strParam.Substring(iIndex, 1) != strParam.Substring(iLength - iIndex, 1))
        {
            &lt;SPAN class="kwrd"&gt;return&lt;/SPAN&gt; &lt;SPAN class="kwrd"&gt;false&lt;/SPAN&gt;;
        }
    }
    &lt;SPAN class="kwrd"&gt;return&lt;/SPAN&gt; &lt;SPAN class="kwrd"&gt;true&lt;/SPAN&gt;;
}&lt;/PRE&gt;
&lt;P&gt;Here the change is subtle (ignore the length calculations at the start, which are a trivial micro-optimization).&lt;/P&gt;&lt;PRE class="csharpcode"&gt;&lt;SPAN class="kwrd"&gt;public&lt;/SPAN&gt; &lt;SPAN class="kwrd"&gt;static&lt;/SPAN&gt; &lt;SPAN class="kwrd"&gt;bool&lt;/SPAN&gt; IsPalindrome(String strParam)
{
    var iLength = strParam.Length;
    var iHalfLen = iLength / 2;
    iLength --;
    &lt;SPAN class="kwrd"&gt;for&lt;/SPAN&gt; (&lt;SPAN class="kwrd"&gt;int&lt;/SPAN&gt; iIndex = 0; iIndex &amp;lt; iHalfLen; iIndex++)
    {
        &lt;SPAN class="kwrd"&gt;if&lt;/SPAN&gt; (strParam[iIndex] != strParam[iLength - iIndex])
        {
            &lt;SPAN class="kwrd"&gt;return&lt;/SPAN&gt; &lt;SPAN class="kwrd"&gt;false&lt;/SPAN&gt;;
        }
    }
    &lt;SPAN class="kwrd"&gt;return&lt;/SPAN&gt; &lt;SPAN class="kwrd"&gt;true&lt;/SPAN&gt;;
}&lt;/PRE&gt;
&lt;P&gt;In this function, instead of comparing one-character long strings, I compare individual characters.  That change, by itself, cause a 4X speed improvement.&lt;/P&gt;
&lt;P&gt;So, there you have it.  The article had more, but the other were trivial, and I couldn’t make them any better.  And in case you think I’m all talk here, each of those rewrites was benchmarked to run 2 to 5 times faster than the original.&lt;/P&gt;
&lt;div class = "shareblock"&gt;&lt;strong&gt;Share this post:&lt;/strong&gt; &lt;a title="Email Some+Better-Written+Custom+String+Methods+using+C%23" href = "mailto:?body=Thought you might like this: http://honestillusion.com/blogs/blog_0/archive/2010/02/02/some-better-written-custom-string-methods-using-c.aspx&amp;subject=Some+Better-Written+Custom+String+Methods+using+C%23"&gt;Email it!&lt;/a&gt; | &lt;a href = "http://del.icio.us/post?url=http://honestillusion.com/blogs/blog_0/archive/2010/02/02/some-better-written-custom-string-methods-using-c.aspx&amp;title=Some+Better-Written+Custom+String+Methods+using+C%23" title="Submit Some+Better-Written+Custom+String+Methods+using+C%23 to del.icio.us" &gt;bookmark it!&lt;/a&gt; | &lt;a href = "http://www.digg.com/submit?url=http://honestillusion.com/blogs/blog_0/archive/2010/02/02/some-better-written-custom-string-methods-using-c.aspx&amp;phase=2" title="Submit Some+Better-Written+Custom+String+Methods+using+C%23 to digg.com"&gt;digg it!&lt;/a&gt; | &lt;a href = "http://reddit.com/submit?url=http://honestillusion.com/blogs/blog_0/archive/2010/02/02/some-better-written-custom-string-methods-using-c.aspx&amp;title=Some+Better-Written+Custom+String+Methods+using+C%23" title="Submit Some+Better-Written+Custom+String+Methods+using+C%23 to reddit.com"&gt;reddit!&lt;/a&gt;&lt;/div&gt;&lt;img src="http://honestillusion.com/aggbug.aspx?PostID=7914" width="1" height="1"&gt;</description><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/Code/default.aspx">Code</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/.Net/default.aspx">.Net</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/Programming/default.aspx">Programming</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/dotnet/default.aspx">dotnet</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/csharp/default.aspx">csharp</category></item><item><title>A ViewComponent extension for Castle MonoRail, Part II</title><link>http://honestillusion.com/blogs/blog_0/archive/2009/08/24/a-viewcomponent-extension-for-castle-monorail-part-ii.aspx</link><pubDate>Tue, 25 Aug 2009 00:44:00 GMT</pubDate><guid isPermaLink="false">0c240a87-1bdc-4d60-96f7-7d0531c1460e:7882</guid><dc:creator>James</dc:creator><slash:comments>0</slash:comments><comments>http://honestillusion.com/blogs/blog_0/comments/7882.aspx</comments><wfw:commentRss>http://honestillusion.com/blogs/blog_0/commentrss.aspx?PostID=7882</wfw:commentRss><description>
  &lt;P&gt;This was intended to be a two-part article.  It was just after I published &lt;A href="http://honestillusion.com/blogs/blog_0/archive/2009/08/24/a-viewcomponent-extension-for-castle-monorail.aspx" target="_blank"&gt;the original article,&lt;/A&gt; I noticed that I’d left out a large part of ViewComponentEx. We continue…..&lt;/P&gt;
&lt;HR /&gt;
&lt;PRE class="c#"&gt;&lt;FONT size="4"&gt;        protected bool RenderOptionalSection(string section) 
        protected bool RenderOptionalSection(string section, string defaultText)&lt;/FONT&gt; &lt;/PRE&gt;
&lt;P&gt;Renders the named section of a block component – if the section is present.  If not, it just silently returns.   The second overload lets you provide some text to be rendered, if that section isn’t given:&lt;/P&gt;
&lt;BLOCKQUOTE&gt;
&lt;P&gt;&lt;FONT size="3"&gt;RenderOptionalSection("tablestart", “&amp;lt;table&amp;gt;”)&lt;/FONT&gt; &lt;/P&gt;&lt;/BLOCKQUOTE&gt;
&lt;P&gt;Returns true if this section was rendered; false, if the section was present.  This seems like a very simple method (and it is), but if your component has a number of different sections for styling (such as the SmartGridViewComponent, which has 18!), this can do wonders to streamline your code.&lt;/P&gt;
&lt;HR /&gt;
&lt;PRE class="c#"&gt;&lt;FONT size="4"&gt;        void RenderComponent&amp;lt;VC&amp;gt;(params string[] componentParams) where VC : ViewComponentEx, new();
        void RenderComponent&amp;lt;VC&amp;gt;(IDictionary componentParams) where VC : ViewComponentEx, new();
        void RenderComponent(ViewComponentEx component, params string[] componentParams); 
        void RenderComponent(ViewComponentEx component, IDictionary componentParams); &lt;/FONT&gt;&lt;/PRE&gt;
&lt;P&gt;This implement, with a slightly different syntax, a technique originally devised by Joey Beninghove.  The idea is to make a ViewComponent which is composite of several other VCs.  The basic syntax is &lt;/P&gt;&lt;PRE class="c#"&gt;&lt;FONT size="4"&gt; RenderComponent&amp;lt;LinkSubmitButtonComponent&amp;gt;("linkText=Search",
             string.Format("formToSubmit={0}", searchFormName));&lt;/FONT&gt;&lt;/PRE&gt;
&lt;P&gt;However, the various overloads allow using an already exist component object, and/or an already built dictionary of options.&lt;/P&gt;
&lt;HR /&gt;

&lt;P&gt;Also include in the source file is the class ViewComponentUsingSiteMap which, like ViewComponentEx, is an abstract base use for creating ViewComponents, but I’ll hold off discussing that until I ready to talk about the VCs the derive from it.&lt;/P&gt;
&lt;div class = "shareblock"&gt;&lt;strong&gt;Share this post:&lt;/strong&gt; &lt;a title="Email A+ViewComponent+extension+for+Castle+MonoRail%2c+Part+II" href = "mailto:?body=Thought you might like this: http://honestillusion.com/blogs/blog_0/archive/2009/08/24/a-viewcomponent-extension-for-castle-monorail-part-ii.aspx&amp;subject=A+ViewComponent+extension+for+Castle+MonoRail%2c+Part+II"&gt;Email it!&lt;/a&gt; | &lt;a href = "http://del.icio.us/post?url=http://honestillusion.com/blogs/blog_0/archive/2009/08/24/a-viewcomponent-extension-for-castle-monorail-part-ii.aspx&amp;title=A+ViewComponent+extension+for+Castle+MonoRail%2c+Part+II" title="Submit A+ViewComponent+extension+for+Castle+MonoRail%2c+Part+II to del.icio.us" &gt;bookmark it!&lt;/a&gt; | &lt;a href = "http://www.digg.com/submit?url=http://honestillusion.com/blogs/blog_0/archive/2009/08/24/a-viewcomponent-extension-for-castle-monorail-part-ii.aspx&amp;phase=2" title="Submit A+ViewComponent+extension+for+Castle+MonoRail%2c+Part+II to digg.com"&gt;digg it!&lt;/a&gt; | &lt;a href = "http://reddit.com/submit?url=http://honestillusion.com/blogs/blog_0/archive/2009/08/24/a-viewcomponent-extension-for-castle-monorail-part-ii.aspx&amp;title=A+ViewComponent+extension+for+Castle+MonoRail%2c+Part+II" title="Submit A+ViewComponent+extension+for+Castle+MonoRail%2c+Part+II to reddit.com"&gt;reddit!&lt;/a&gt;&lt;/div&gt;&lt;img src="http://honestillusion.com/aggbug.aspx?PostID=7882" width="1" height="1"&gt;</description><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/Code/default.aspx">Code</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/.Net/default.aspx">.Net</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/Programming/default.aspx">Programming</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/dotnet/default.aspx">dotnet</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/csharp/default.aspx">csharp</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/castle/default.aspx">castle</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/monorail/default.aspx">monorail</category></item><item><title>A ViewComponent extension for Castle MonoRail</title><link>http://honestillusion.com/blogs/blog_0/archive/2009/08/24/a-viewcomponent-extension-for-castle-monorail.aspx</link><pubDate>Mon, 24 Aug 2009 11:21:08 GMT</pubDate><guid isPermaLink="false">0c240a87-1bdc-4d60-96f7-7d0531c1460e:7881</guid><dc:creator>James</dc:creator><slash:comments>1</slash:comments><comments>http://honestillusion.com/blogs/blog_0/comments/7881.aspx</comments><wfw:commentRss>http://honestillusion.com/blogs/blog_0/commentrss.aspx?PostID=7881</wfw:commentRss><description>
  &lt;p&gt;I’ve been rewriting my website, njtheater.com, (very slowly) as a Castle MonoRail application.  Along the way, I’ve written a number of ViewComponent and other elements.  Many of these were of general use, so I’ve added them to the CastleContib project, and documented them in the using.castleproject.org wiki.&lt;/p&gt;  &lt;p&gt;Two problem there: First, some of the items I wrote don’t fit into an exist category in CastleContrib (There’s one for ViewComponents, which I’ve stick a filter into, but putting a Controller base class there seemed wrong).  Second, CastleContrib &amp;amp; using.castleproject.org seem to be somewhat of a black hole.  No one seems to look there for information about the Castle Project (which is kind of a shame, since that’s exactly it’s purpose).  &lt;/p&gt;  &lt;p&gt;On the other hand, blogs posts about Castle are turning up everywhere.  We’ve even now got an &lt;a href="http://pipes.yahoo.com/pipes/pipe.run?_id=bGjr2c1s3hGi5qx20EypaA&amp;amp;_render=rss&amp;amp;limit=200" target="_blank"&gt;aggregated blog feed specific to Castle&lt;/a&gt;.  So, I figured, I start using my blog to talk about what I’ve written.&lt;/p&gt;  &lt;p&gt;In fact, one article I discovered on that aggregator was Andy Pike’s “Integrating Gravatar with Castle MonoRail” inwhich he discusses a Helper object for Monorail which creates Gravatars for use’s email addresses.  It was written last January.  The only thing is, I’ve written (and added to CastleContrib) a Gravatar component three months earlier.  That was going to be the topic of my first MonoRail blog post (and I will be my second), but first, I figure I should talk about the base class I once for all my ViewComponents, which I’ve given the rather imaginative name of ViewComponentEx.&lt;/p&gt;  &lt;p&gt;ViewComponentEx derives from ViewComponent, and can be used as a “drop-in” replacement for it, as the base class for your ViewComponents.  It provides a number of simple methods to help building ViewComponents.&lt;/p&gt;  &lt;pre class="c#"&gt;&lt;font size="4"&gt;void ConfirmSectionPresent(string section);&lt;/font&gt;&lt;/pre&gt;

&lt;blockquote&gt;
  &lt;p&gt;Throws an exception if the given section is not present. &lt;/p&gt;
&lt;/blockquote&gt;

&lt;pre class="c#"&gt;&lt;font size="4"&gt;string GetSectionText(string section);&lt;/font&gt;&lt;/pre&gt;

&lt;blockquote&gt;
  &lt;p&gt;Get the text of a section as a string.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;pre class="c#"&gt;&lt;font size="4"&gt;string GetBodyText();&lt;/font&gt;&lt;/pre&gt;

&lt;blockquote&gt;
  &lt;p&gt;Get the text of the body of a block component (without section)&lt;/p&gt;
&lt;/blockquote&gt;

&lt;pre class="c#"&gt;&lt;font size="4"&gt;void RenderTextFormat(string format, params object[] args);&lt;/font&gt;&lt;/pre&gt;

&lt;blockquote&gt;
  &lt;p&gt;Renders the text, formatted. Just like String.Format() &lt;/p&gt;
&lt;/blockquote&gt;

&lt;pre class="c#"&gt;&lt;font size="4"&gt;string GetParamValue(string key, string defaultValue);&lt;/font&gt;&lt;/pre&gt;

&lt;pre class="c#"&gt;&lt;font size="4"&gt;bool GetParamValue(string key, bool defaultValue);&lt;/font&gt;&lt;/pre&gt;

&lt;pre class="c#"&gt;&lt;font size="4"&gt;E GetParamValue(string key, E defaultValue) where E : struct;&lt;/font&gt;&lt;/pre&gt;

&lt;blockquote&gt;
  &lt;p&gt;Gets a parameter value, with a default. Overloaded to handle string, boolean, or Enum value. &lt;/p&gt;
&lt;/blockquote&gt;

&lt;pre class="c#"&gt;&lt;font size="4"&gt;Castle.Core.Logging.ILogger Logger { get; set; }&lt;/font&gt;&lt;/pre&gt;

&lt;blockquote&gt;
  &lt;p&gt;A property for the system Logger. Automatically wired by Windsor, if active and a Logger is defined in the container. Default to NullLogger, otherwise.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;pre class="c#"&gt;&lt;font size="4"&gt;string MakeUniqueId(string prefix);&lt;/font&gt;&lt;/pre&gt;

&lt;blockquote&gt;
  &lt;p&gt;Makes an unique id. The given prefix is prepended to the generated number. The ID isn't actually guaranteed to be unique (which would require using all 32 digits of the guid). But this produce ids sufficiently distinctive to generate multiple controls on a page.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt;Code available here: &lt;a href="http://honestillusion.com/files/folders/castle/entry7880.aspx" target="_blank"&gt;ViewComponentex.cs&lt;/a&gt;&lt;/p&gt;
&lt;div class = "shareblock"&gt;&lt;strong&gt;Share this post:&lt;/strong&gt; &lt;a title="Email A+ViewComponent+extension+for+Castle+MonoRail" href = "mailto:?body=Thought you might like this: http://honestillusion.com/blogs/blog_0/archive/2009/08/24/a-viewcomponent-extension-for-castle-monorail.aspx&amp;subject=A+ViewComponent+extension+for+Castle+MonoRail"&gt;Email it!&lt;/a&gt; | &lt;a href = "http://del.icio.us/post?url=http://honestillusion.com/blogs/blog_0/archive/2009/08/24/a-viewcomponent-extension-for-castle-monorail.aspx&amp;title=A+ViewComponent+extension+for+Castle+MonoRail" title="Submit A+ViewComponent+extension+for+Castle+MonoRail to del.icio.us" &gt;bookmark it!&lt;/a&gt; | &lt;a href = "http://www.digg.com/submit?url=http://honestillusion.com/blogs/blog_0/archive/2009/08/24/a-viewcomponent-extension-for-castle-monorail.aspx&amp;phase=2" title="Submit A+ViewComponent+extension+for+Castle+MonoRail to digg.com"&gt;digg it!&lt;/a&gt; | &lt;a href = "http://reddit.com/submit?url=http://honestillusion.com/blogs/blog_0/archive/2009/08/24/a-viewcomponent-extension-for-castle-monorail.aspx&amp;title=A+ViewComponent+extension+for+Castle+MonoRail" title="Submit A+ViewComponent+extension+for+Castle+MonoRail to reddit.com"&gt;reddit!&lt;/a&gt;&lt;/div&gt;&lt;img src="http://honestillusion.com/aggbug.aspx?PostID=7881" width="1" height="1"&gt;</description><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/Code/default.aspx">Code</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/.Net/default.aspx">.Net</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/Programming/default.aspx">Programming</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/dotnet/default.aspx">dotnet</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/csharp/default.aspx">csharp</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/castle/default.aspx">castle</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/monorail/default.aspx">monorail</category></item><item><title>#songsincode : The Turtle’s “Happy Together”</title><link>http://honestillusion.com/blogs/blog_0/archive/2009/08/22/songsincode-the-turtle-s-happy-together.aspx</link><pubDate>Sat, 22 Aug 2009 15:26:29 GMT</pubDate><guid isPermaLink="false">0c240a87-1bdc-4d60-96f7-7d0531c1460e:7879</guid><dc:creator>James</dc:creator><slash:comments>0</slash:comments><comments>http://honestillusion.com/blogs/blog_0/comments/7879.aspx</comments><wfw:commentRss>http://honestillusion.com/blogs/blog_0/commentrss.aspx?PostID=7879</wfw:commentRss><description>
  &lt;pre class="c#"&gt;
    &lt;font size="4"&gt;(Me + you) &amp;amp;&amp;amp;  (you + me)
var nomatter = dice.toss(); assert (it != null)
me.Only1(you); assert(you == me.Only1());
(Me + you).happy  = so;&lt;/font&gt;
  &lt;/pre&gt;

&lt;pre class="c#"&gt; &lt;/pre&gt;

&lt;p&gt;(more on the meme &lt;a href="http://www.wait-till-i.com/2009/08/21/wow-so-that-is-how-memes-happen-songsincode/" target="_blank"&gt;here&lt;/a&gt;)&lt;/p&gt;

&lt;pre class="c#"&gt; &lt;/pre&gt;

&lt;pre class="c#"&gt; &lt;/pre&gt;
&lt;div class = "shareblock"&gt;&lt;strong&gt;Share this post:&lt;/strong&gt; &lt;a title="Email %23songsincode+%3a+The+Turtle%e2%80%99s+%e2%80%9cHappy+Together%e2%80%9d" href = "mailto:?body=Thought you might like this: http://honestillusion.com/blogs/blog_0/archive/2009/08/22/songsincode-the-turtle-s-happy-together.aspx&amp;subject=%23songsincode+%3a+The+Turtle%e2%80%99s+%e2%80%9cHappy+Together%e2%80%9d"&gt;Email it!&lt;/a&gt; | &lt;a href = "http://del.icio.us/post?url=http://honestillusion.com/blogs/blog_0/archive/2009/08/22/songsincode-the-turtle-s-happy-together.aspx&amp;title=%23songsincode+%3a+The+Turtle%e2%80%99s+%e2%80%9cHappy+Together%e2%80%9d" title="Submit %23songsincode+%3a+The+Turtle%e2%80%99s+%e2%80%9cHappy+Together%e2%80%9d to del.icio.us" &gt;bookmark it!&lt;/a&gt; | &lt;a href = "http://www.digg.com/submit?url=http://honestillusion.com/blogs/blog_0/archive/2009/08/22/songsincode-the-turtle-s-happy-together.aspx&amp;phase=2" title="Submit %23songsincode+%3a+The+Turtle%e2%80%99s+%e2%80%9cHappy+Together%e2%80%9d to digg.com"&gt;digg it!&lt;/a&gt; | &lt;a href = "http://reddit.com/submit?url=http://honestillusion.com/blogs/blog_0/archive/2009/08/22/songsincode-the-turtle-s-happy-together.aspx&amp;title=%23songsincode+%3a+The+Turtle%e2%80%99s+%e2%80%9cHappy+Together%e2%80%9d" title="Submit %23songsincode+%3a+The+Turtle%e2%80%99s+%e2%80%9cHappy+Together%e2%80%9d to reddit.com"&gt;reddit!&lt;/a&gt;&lt;/div&gt;&lt;img src="http://honestillusion.com/aggbug.aspx?PostID=7879" width="1" height="1"&gt;</description><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/Code/default.aspx">Code</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/.Net/default.aspx">.Net</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/Programming/default.aspx">Programming</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/music/default.aspx">music</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/dotnet/default.aspx">dotnet</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/csharp/default.aspx">csharp</category></item><item><title>Code Tune-Up: Shuffling a List</title><link>http://honestillusion.com/blogs/blog_0/archive/2009/08/16/code-tune-up-shuffling-a-list.aspx</link><pubDate>Sun, 16 Aug 2009 23:14:11 GMT</pubDate><guid isPermaLink="false">0c240a87-1bdc-4d60-96f7-7d0531c1460e:7877</guid><dc:creator>James</dc:creator><slash:comments>0</slash:comments><comments>http://honestillusion.com/blogs/blog_0/comments/7877.aspx</comments><wfw:commentRss>http://honestillusion.com/blogs/blog_0/commentrss.aspx?PostID=7877</wfw:commentRss><description>Over on CodeProject, I spotted an article by Mahdi Yousefi called "
&lt;a href="http://www.codeproject.com/KB/validation/aspnet_capcha.aspx" target="_blank"&gt;Creating an ASP.NET captcha using jQuery and s3capcha”.&lt;/a&gt;
&lt;pre class="c#"&gt;&lt;font size="4"&gt;public static List&amp;lt;int&amp;gt; shuffle(List&amp;lt;int&amp;gt; input)
{
    List&amp;lt;int&amp;gt; output = new List&amp;lt;int&amp;gt;();
    Random rnd = new Random();
 
    int FIndex;
    while (input.Count &amp;gt; 0)
    {
        FIndex = rnd.Next(0, input.Count);
        output.Add(input[FIndex]);
        input.RemoveAt(FIndex);
    }
 
    input.Clear();
    input = null;
    rnd = null;
 
    return output;
}&lt;/font&gt;&lt;/pre&gt;
&lt;p&gt;So, what’s wrong with this?  Well, let’s see:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;It takes a List as a parameter and returns a list.  This is rather limiting.  What if we have array we want to shuffle? &lt;/li&gt;

  &lt;li&gt;It takes and returns a list of &lt;strong&gt;integers. &lt;/strong&gt;Again rather limiting.  What if we had strings or say, PlayingCard objects we want to shuffle? &lt;/li&gt;

  &lt;li&gt;It creates a new Random object every time it’s called.  Two problems there.  First, when a Random object is created, a seed is produced.  This is a fairly time-consuming task, which you don’t want to do repeatedly necessarily.  Second, when the default constructor is called, like here, the seed is initialized using the internal clock’s TickCount --- which is the time in &lt;em&gt;milliseconds&lt;/em&gt;.  If you called shuffle() twice within a millisecond -– not unreasonable if you were writing a game – the Random objects would be using the same seed, and produce the same sequence. &lt;/li&gt;

  &lt;li&gt;It creates a new list for output.  This  is a problem only in that it’s a time expense we might as well avoid if possible.  It also builds this list by repeated calls to Add(), but without specifying an initial size, meaning that Add() will frequently have to resize the list to keep expanding it.  The fix to this would be trivial.  Just create the new list as “new List&amp;lt;int&amp;gt;(input.Count);”.  But as you’ll see, this won’t be necessary. &lt;/li&gt;

  &lt;li&gt;It destroys the list input.  In fact, it destroys it three times over: First by removing all of it’s items.  Then by calling Clear() on the empty list.  Then by setting the local reference to null.  That last one might cause it to be garbage-collected a couple microseconds earlier – if the calling routine didn’t hold a reference to it. I don’t want to claim this as a “Problem”, as much as a “Behavior” – It’s just something it does, so if our replacement does that as well (as it will), we haven’t lost anything.  But, if you nevertheless thing that &lt;em&gt;is&lt;/em&gt; a problem, don’t worry, we’ll address that to. &lt;/li&gt;

  &lt;li&gt;It removes that items from the list using Remove() – This is a very time-consuming method on Lists (which, contrary to popular belief are not linked-lists, but are internally implement as arrays).  One call to List.Remove() is O(N) by itself.  Since it’s called in a loop, that makes the complicity of this method O(N^2).  Clearly that’s something we should avoid. &lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;So,  let’s tackle these.  First the signature.  we say we want a List, but we really only want so features of a list – that usually means we want an interface.  And we want to be usable for List of all types, so it’s wants to be generic:&lt;/p&gt;
&lt;pre class="c#"&gt;&lt;font size="4"&gt;public static IList&amp;lt;T&amp;gt; Shuffle&amp;lt;T&amp;gt;(this IList&amp;lt;T&amp;gt; input)&lt;/font&gt;&lt;/pre&gt;
&lt;p&gt;IList has just the features we need, and allows us to pass different collection types (notably arrays) to the method.  I’ve also implemented it as an extension method, because it seemed more useful that way.  But to be an extension method, it has to be in a static class, which brings us to our next change:&lt;/p&gt;
&lt;pre class="c#"&gt;&lt;font size="4"&gt;static class Helper
{
       static readonly Random rnd = new Random();
    // :&lt;/font&gt;&lt;/pre&gt;
&lt;p&gt;I’ve moved that Random object to be a static member.  That way, only one is created &amp;amp; initialized, and every call to Shuffle reuses the same one.&lt;/p&gt;
&lt;p&gt;Next is that main loop:&lt;/p&gt;
&lt;pre class="c#"&gt;&lt;font size="4"&gt;for(var top = input.Count -1; top &amp;gt; 1; --top)
{
    var swap = rnd.Next(0, top);
    T tmp = input[top];
    input[top] = input[swap];
    input[swap] = tmp;
}&lt;/font&gt;&lt;/pre&gt;
&lt;p&gt;Here’s where we see the major change to the implementation. Both method use basically the same algorithm, but instead of building a new List, I move the elements around within the same list.  Essentially, I’m doing the same thing, if you imagine the two arrays occupying that same space – as one grows small the other grows bigger.  &lt;/p&gt;
&lt;p&gt;And with that, we’re done.  Since the original List is now shuffled, we could return void, but by returning the input, we can allow chaining (and it also maintains the original method signature)&lt;/p&gt;
&lt;p&gt;So, How does it work ?  Here’s a quick example, showing off some of it’s new abilities:&lt;/p&gt;
&lt;pre class="c#"&gt;&lt;font size="4"&gt;        string[] A = {"A", "B", "C", "D", "E", "F", "G"};
        A.Shuffle().Print();

output: D-F-A-G-B-E-C-&lt;/font&gt;&lt;/pre&gt;
&lt;p&gt;Print() is a simple-minded extension method which just takes a list and prints it’s elements separated by dashes.  Good for demos but not much else.  Also for these examples, I’ve hard-coded the seed for Random to be 1234, so the sequence is always repeated.  Again, good for demos, but not for production work.&lt;/p&gt;
&lt;p&gt;But, you said you didn’t want the original list destroyed. (yes, you did in fact say that!).  No problem, we’ll just write a second method, and since the problem definition requires two lists, there’s no shame in eating the cost of creating a copy of the input list.  To keep it simple, I’ll also create &amp;amp; return a List&amp;lt;&amp;gt; regardless of what type of IList&amp;lt;&amp;gt; you passed in.  &lt;/p&gt;
&lt;pre class="c#"&gt; &lt;font size="4"&gt; return new List&amp;lt;T&amp;gt;(input).Shuffle();&lt;/font&gt;&lt;/pre&gt;
&lt;p&gt;But that brings us to another key point.  The only thing that the input is being used for is to seed the new List, and that ctor doesn’t take an IList&amp;lt;&amp;gt;, it takes the much more common IEnumerable&amp;lt;&amp;gt; (which IList just happens to be a descendant of).  So, we might as well make that our input parameter.&lt;/p&gt;
&lt;pre class="c#"&gt;&lt;font size="4"&gt;public static IList&amp;lt;T&amp;gt; ShuffleCopy&amp;lt;T&amp;gt;(this IEnumerable&amp;lt;T&amp;gt; input)
{        return new List&amp;lt;T&amp;gt;(input).Shuffle();    }&lt;/font&gt;      &lt;/pre&gt;
&lt;p&gt;With this, we can do some interesting things, since you input doesn’t have to be a collection at all:&lt;/p&gt;
&lt;pre class="c#"&gt;&lt;font size="4"&gt;        Enumerable.Range(1,10).ShuffleCopy().Print();

output:  1-5-7-9-10-2-6-3-8-4-&lt;/font&gt;&lt;/pre&gt;
&lt;p&gt;Here’s the full source code:&lt;/p&gt;
&lt;pre class="c#"&gt;&lt;font size="4"&gt;static class Helper
{
    static readonly Random rnd = new Random();
       
    public static IList&amp;lt;T&amp;gt; Shuffle&amp;lt;T&amp;gt;(this IList&amp;lt;T&amp;gt; input)
    {
        for(var top = input.Count -1; top &amp;gt; 1; --top)
        {
            var swap = rnd.Next(0, top);
            T tmp = input[top];
            input[top] = input[swap];
            input[swap] = tmp;
        }
    
        return input;
    }      
    
    public static IList&amp;lt;T&amp;gt; ShuffleCopy&amp;lt;T&amp;gt;(this IEnumerable&amp;lt;T&amp;gt; input)
    {        return new List&amp;lt;T&amp;gt;(input).Shuffle();    }      
    
    public static void Print&amp;lt;T&amp;gt;(this IList&amp;lt;T&amp;gt; list)
    {
        foreach(T t in list)
        {
                Console.Write("{0}-", t);
        }
        Console.WriteLine();
    }
}&lt;/font&gt;&lt;/pre&gt;
&lt;div class = "shareblock"&gt;&lt;strong&gt;Share this post:&lt;/strong&gt; &lt;a title="Email Code+Tune-Up%3a+Shuffling+a+List" href = "mailto:?body=Thought you might like this: http://honestillusion.com/blogs/blog_0/archive/2009/08/16/code-tune-up-shuffling-a-list.aspx&amp;subject=Code+Tune-Up%3a+Shuffling+a+List"&gt;Email it!&lt;/a&gt; | &lt;a href = "http://del.icio.us/post?url=http://honestillusion.com/blogs/blog_0/archive/2009/08/16/code-tune-up-shuffling-a-list.aspx&amp;title=Code+Tune-Up%3a+Shuffling+a+List" title="Submit Code+Tune-Up%3a+Shuffling+a+List to del.icio.us" &gt;bookmark it!&lt;/a&gt; | &lt;a href = "http://www.digg.com/submit?url=http://honestillusion.com/blogs/blog_0/archive/2009/08/16/code-tune-up-shuffling-a-list.aspx&amp;phase=2" title="Submit Code+Tune-Up%3a+Shuffling+a+List to digg.com"&gt;digg it!&lt;/a&gt; | &lt;a href = "http://reddit.com/submit?url=http://honestillusion.com/blogs/blog_0/archive/2009/08/16/code-tune-up-shuffling-a-list.aspx&amp;title=Code+Tune-Up%3a+Shuffling+a+List" title="Submit Code+Tune-Up%3a+Shuffling+a+List to reddit.com"&gt;reddit!&lt;/a&gt;&lt;/div&gt;&lt;img src="http://honestillusion.com/aggbug.aspx?PostID=7877" width="1" height="1"&gt;</description><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/Code/default.aspx">Code</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/.Net/default.aspx">.Net</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/Programming/default.aspx">Programming</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/dotnet/default.aspx">dotnet</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/csharp/default.aspx">csharp</category></item><item><title>Posts from Comments: QuickDataBind</title><link>http://honestillusion.com/blogs/blog_0/archive/2009/07/28/posts-from-comments-quickdatabind.aspx</link><pubDate>Tue, 28 Jul 2009 10:49:49 GMT</pubDate><guid isPermaLink="false">0c240a87-1bdc-4d60-96f7-7d0531c1460e:7873</guid><dc:creator>James</dc:creator><slash:comments>0</slash:comments><comments>http://honestillusion.com/blogs/blog_0/comments/7873.aspx</comments><wfw:commentRss>http://honestillusion.com/blogs/blog_0/commentrss.aspx?PostID=7873</wfw:commentRss><description>
  &lt;p&gt;You may have noticed that I don’t write on this blog much.  But the thing is I &lt;em&gt;do&lt;/em&gt; write a lot on the inter-webs about technical matters --- I just don’t to it here.  Usually, I find something interesting on someone else’s blog, and then write an improvement in the comments.  So, my work goes to helping other people’s pagerank.  I figure this has got to stop… To this end, I start a series where I turn comments I made on other blogs into posts on this one….&lt;/p&gt;  &lt;p&gt; &lt;/p&gt;  &lt;p&gt;To start us off, a few days ago, &lt;a href="http://geekswithblogs.net/samerpaul/archive/2009/07/22/listview-extension-i-thought-irsquod-sharehellip.aspx" target="_blank"&gt;Samer wrote about an extension method&lt;/a&gt; he created for ListView: &lt;/p&gt;  &lt;pre class="c#"&gt;public static ListView QuickDataBind(this ListView myListView, object myDataSource)
    {
        myListView.DataSource = myDataSource;
        myListView.DataBind();
        return myListView;
    }&lt;/pre&gt;

&lt;p&gt;Now, this is all well and good.  but why are we limiting ourselves to just ListViews?  Many ASP.NET WebControl take a datasource and use that idiom.  Why not make an generic extension method to handle all of them?&lt;/p&gt;

&lt;pre class="c#"&gt;public static T QuickDataBind(this T myDataBoundControl, object myDataSource) 
        where T: BaseDataBoundControl
{
        myDataBoundControl.DataSource = myDataSource;
        myDataBoundControl.DataBind();
        return myDataBoundControl;
}&lt;/pre&gt;
It's still called exactly the same well: 

&lt;pre class="c#"&gt;       myGridView.QuickDataBind(myDS);&lt;/pre&gt;
but now it can be used on ListViews, GridView, DropDownLists DataGrids, Repeaters or anything else that uses a DataSOurce. 


&lt;div class = "shareblock"&gt;&lt;strong&gt;Share this post:&lt;/strong&gt; &lt;a title="Email Posts+from+Comments%3a+QuickDataBind" href = "mailto:?body=Thought you might like this: http://honestillusion.com/blogs/blog_0/archive/2009/07/28/posts-from-comments-quickdatabind.aspx&amp;subject=Posts+from+Comments%3a+QuickDataBind"&gt;Email it!&lt;/a&gt; | &lt;a href = "http://del.icio.us/post?url=http://honestillusion.com/blogs/blog_0/archive/2009/07/28/posts-from-comments-quickdatabind.aspx&amp;title=Posts+from+Comments%3a+QuickDataBind" title="Submit Posts+from+Comments%3a+QuickDataBind to del.icio.us" &gt;bookmark it!&lt;/a&gt; | &lt;a href = "http://www.digg.com/submit?url=http://honestillusion.com/blogs/blog_0/archive/2009/07/28/posts-from-comments-quickdatabind.aspx&amp;phase=2" title="Submit Posts+from+Comments%3a+QuickDataBind to digg.com"&gt;digg it!&lt;/a&gt; | &lt;a href = "http://reddit.com/submit?url=http://honestillusion.com/blogs/blog_0/archive/2009/07/28/posts-from-comments-quickdatabind.aspx&amp;title=Posts+from+Comments%3a+QuickDataBind" title="Submit Posts+from+Comments%3a+QuickDataBind to reddit.com"&gt;reddit!&lt;/a&gt;&lt;/div&gt;&lt;img src="http://honestillusion.com/aggbug.aspx?PostID=7873" width="1" height="1"&gt;</description><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/Code/default.aspx">Code</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/.Net/default.aspx">.Net</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/Programming/default.aspx">Programming</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/dotnet/default.aspx">dotnet</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/csharp/default.aspx">csharp</category></item><item><title>DEV102's Programming Job Interview Challenge #6 </title><link>http://honestillusion.com/blogs/blog_0/archive/2008/06/02/dev102-s-programming-job-interview-challenge-6.aspx</link><pubDate>Mon, 02 Jun 2008 14:16:00 GMT</pubDate><guid isPermaLink="false">0c240a87-1bdc-4d60-96f7-7d0531c1460e:4914</guid><dc:creator>James</dc:creator><slash:comments>0</slash:comments><comments>http://honestillusion.com/blogs/blog_0/comments/4914.aspx</comments><wfw:commentRss>http://honestillusion.com/blogs/blog_0/commentrss.aspx?PostID=4914</wfw:commentRss><description>
  &lt;p&gt;Another week, another C# interview question from the good folk's at Dev102.com -- Although I use the term "good folks" advisedly, as this week they did not even acknowledge the solution I posted for last weeks puzzle (which was both correct, and, I believe, the first blog post about it).&lt;/p&gt;

&lt;p&gt;Anyway, time to move on to &lt;a href="http://www.dev102.com/2008/06/02/a-programming-job-interview-challenge-6-c-games/"&gt;this week's question&lt;/a&gt;. &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Look at the following Code segment written in C#:&lt;/p&gt;
&lt;div&gt;
&lt;div style="border-style:none;padding:0px;overflow:visible;font-size:8pt;width:100%;color:black;line-height:12pt;"&gt;
&lt;pre style="border-style:none;margin:0em;padding:0px;overflow:visible;font-size:8pt;width:100%;color:black;line-height:12pt;"&gt;&lt;span&gt;   1:&lt;/span&gt; ArrayList a = &lt;span&gt;new&lt;/span&gt; ArrayList();&lt;/pre&gt;
&lt;pre style="border-style:none;margin:0em;padding:0px;overflow:visible;font-size:8pt;width:100%;color:black;line-height:12pt;"&gt;&lt;span&gt;   2:&lt;/span&gt; ArrayList b = &lt;span&gt;new&lt;/span&gt; ArrayList();&lt;/pre&gt;
&lt;pre style="border-style:none;margin:0em;padding:0px;overflow:visible;font-size:8pt;width:100%;color:black;line-height:12pt;"&gt;&lt;span&gt;   3:&lt;/span&gt;&lt;/pre&gt;
&lt;pre style="border-style:none;margin:0em;padding:0px;overflow:visible;font-size:8pt;width:100%;color:black;line-height:12pt;"&gt;&lt;span&gt;   4:&lt;/span&gt; a.Add(1);&lt;/pre&gt;
&lt;pre style="border-style:none;margin:0em;padding:0px;overflow:visible;font-size:8pt;width:100%;color:black;line-height:12pt;"&gt;&lt;span&gt;   5:&lt;/span&gt; b.Add(1);&lt;/pre&gt;
&lt;pre style="border-style:none;margin:0em;padding:0px;overflow:visible;font-size:8pt;width:100%;color:black;line-height:12pt;"&gt;&lt;span&gt;   6:&lt;/span&gt; a.Add(2);&lt;/pre&gt;
&lt;pre style="border-style:none;margin:0em;padding:0px;overflow:visible;font-size:8pt;width:100%;color:black;line-height:12pt;"&gt;&lt;span&gt;   7:&lt;/span&gt; b.Add(2.0);&lt;/pre&gt;
&lt;pre style="border-style:none;margin:0em;padding:0px;overflow:visible;font-size:8pt;width:100%;color:black;line-height:12pt;"&gt;&lt;span&gt;   8:&lt;/span&gt;&lt;/pre&gt;
&lt;pre style="border-style:none;margin:0em;padding:0px;overflow:visible;font-size:8pt;width:100%;color:black;line-height:12pt;"&gt;&lt;span&gt;   9:&lt;/span&gt; Console.WriteLine((a[0] == b[0]));&lt;/pre&gt;
&lt;pre style="border-style:none;margin:0em;padding:0px;overflow:visible;font-size:8pt;width:100%;color:black;line-height:12pt;"&gt;&lt;span&gt;  10:&lt;/span&gt; Console.WriteLine((a[1] == b[1]));&lt;/pre&gt;
&lt;/div&gt;
&lt;/div&gt;
What will be typed into the console? And &lt;b&gt;&lt;span style="text-decoration:underline;"&gt;WHY?&lt;/span&gt;&lt;/b&gt;&lt;/blockquote&gt;

&lt;p&gt; &lt;/p&gt;

&lt;p&gt; This one is fairly trivial (They seem to be alternating between difficult and easy questions).  And, as requested, I formulated my answer before typing it into VS (actually, I copy'n'pasted in SnippetCompiler), but the compiler DID confirm the answer I'd already theorized.&lt;/p&gt;
&lt;p&gt;This answer is short enough that we can use the cool "white-on-white; select to see it" trick--- However, RSS feed (and apparently the theme of this blog) seem to ignore the color style, so it's probably visible to you below.. &lt;/p&gt;

&lt;p&gt; &lt;/p&gt;
&lt;p&gt; &lt;/p&gt;
&lt;p&gt; &lt;/p&gt;
&lt;div style="color:white;"&gt;
&lt;p&gt;ArrayList is deep-down, just an object[].  To store an valuetype, like an int or float, in an ArrayList, that value would first have to be boxed.  Each valuetype is boxed separately, in distinct objects, even if they do happen to have the same value. When we get to the WriteLines, we are just performing (object) == (object) (actually, Object.ReferenceEquals(object1, object2); )  ReferenceEquals knows nothing about unboxing.  It just asks, "Are these two references pointing to the exact same object?".  For any two boxed objects, regardless of their value, the answer would be "No".  Hence, both lines print "False".&lt;/p&gt;
&lt;/div&gt;
&lt;p&gt; &lt;/p&gt;
&lt;p&gt; &lt;/p&gt;
&lt;p&gt; &lt;/p&gt;

&lt;p&gt; (select the blank space above)&lt;/p&gt;
&lt;br /&gt;
&lt;div class = "shareblock"&gt;&lt;strong&gt;Share this post:&lt;/strong&gt; &lt;a title="Email DEV102%27s+Programming+Job+Interview+Challenge+%236+" href = "mailto:?body=Thought you might like this: http://honestillusion.com/blogs/blog_0/archive/2008/06/02/dev102-s-programming-job-interview-challenge-6.aspx&amp;subject=DEV102%27s+Programming+Job+Interview+Challenge+%236+"&gt;Email it!&lt;/a&gt; | &lt;a href = "http://del.icio.us/post?url=http://honestillusion.com/blogs/blog_0/archive/2008/06/02/dev102-s-programming-job-interview-challenge-6.aspx&amp;title=DEV102%27s+Programming+Job+Interview+Challenge+%236+" title="Submit DEV102%27s+Programming+Job+Interview+Challenge+%236+ to del.icio.us" &gt;bookmark it!&lt;/a&gt; | &lt;a href = "http://www.digg.com/submit?url=http://honestillusion.com/blogs/blog_0/archive/2008/06/02/dev102-s-programming-job-interview-challenge-6.aspx&amp;phase=2" title="Submit DEV102%27s+Programming+Job+Interview+Challenge+%236+ to digg.com"&gt;digg it!&lt;/a&gt; | &lt;a href = "http://reddit.com/submit?url=http://honestillusion.com/blogs/blog_0/archive/2008/06/02/dev102-s-programming-job-interview-challenge-6.aspx&amp;title=DEV102%27s+Programming+Job+Interview+Challenge+%236+" title="Submit DEV102%27s+Programming+Job+Interview+Challenge+%236+ to reddit.com"&gt;reddit!&lt;/a&gt;&lt;/div&gt;&lt;img src="http://honestillusion.com/aggbug.aspx?PostID=4914" width="1" height="1"&gt;</description><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/Code/default.aspx">Code</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/.Net/default.aspx">.Net</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/dotnet/default.aspx">dotnet</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/csharp/default.aspx">csharp</category></item><item><title>DEV102's Programming Job Interview Challenge #4</title><link>http://honestillusion.com/blogs/blog_0/archive/2008/05/23/dev102-s-programming-job-interview-challenge-4.aspx</link><pubDate>Fri, 23 May 2008 13:58:31 GMT</pubDate><guid isPermaLink="false">0c240a87-1bdc-4d60-96f7-7d0531c1460e:4766</guid><dc:creator>James</dc:creator><slash:comments>1</slash:comments><comments>http://honestillusion.com/blogs/blog_0/comments/4766.aspx</comments><wfw:commentRss>http://honestillusion.com/blogs/blog_0/commentrss.aspx?PostID=4766</wfw:commentRss><description>
  &lt;p&gt;The folks at Dev102.com are offering weekly programming challenges, where they offer questions, and let bloggers post about them.  I meant to write an answer for last week, but never got around to it.  Just as well -- my answer would have been wrong.  SO, let's move on to &lt;a href="http://www.dev102.com/2008/05/19/a-programming-job-interview-challenge-4/"&gt;this week's&lt;/a&gt;:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;em&gt;How would you implement the following method: Foo(7) == 17 and Foo(17) == 7. Any other input to that method is not defined so you can return anything you want. Just follow those rules:&lt;/em&gt;&lt;/p&gt;    &lt;ul&gt;     &lt;li&gt;&lt;em&gt;Conditional statements (if, switch, …) are not allowed. &lt;/em&gt;&lt;/li&gt;      &lt;li&gt;&lt;em&gt;Usage of containers (hash tables, arrays, …) are not allowed. &lt;/em&gt;&lt;/li&gt;   &lt;/ul&gt; &lt;/blockquote&gt;  &lt;p&gt;My first thought was, since we can't use conditional statements, to use conditional &lt;em&gt;expressions&lt;/em&gt; instead:&lt;/p&gt;  &lt;p&gt;&lt;font face="Courier New"&gt;int foo(int n)      &lt;br /&gt;{      &lt;br /&gt;    return (n==7) ? 17 : (n==17) ? 7 : n;      &lt;br /&gt;} &lt;/font&gt;&lt;/p&gt;  &lt;p&gt; &lt;/p&gt;  &lt;p&gt;But clearly, that is just cheating.  (And, besides, it turns out, it's not the best solution).&lt;/p&gt;  &lt;p&gt;My next attempt was to use subtraction to create factors of zero.&lt;/p&gt;  &lt;p&gt;&lt;font face="Courier New"&gt;int foo(int n)      &lt;br /&gt;{      &lt;br /&gt;    return n + (10 * (n-17) * (n-6)) + (-10 * (n-16) * (n-7))  ;      &lt;br /&gt;} &lt;/font&gt;&lt;/p&gt;  &lt;p&gt;There may be a formula in there that works, but that one doesn't, and before I found it, I stumble upon the &lt;em&gt;correct &lt;/em&gt;solution, which was just sitting there staring me in the face:&lt;/p&gt;  &lt;p&gt;&lt;font face="Courier New"&gt;int foo(int n)      &lt;br /&gt;{      &lt;br /&gt;    return 24-n;      &lt;br /&gt;} &lt;/font&gt;&lt;/p&gt;  &lt;p&gt;&lt;font face="Courier New"&gt;&lt;/font&gt;&lt;/p&gt;  &lt;p&gt;Yep, it's just that simple.&lt;/p&gt;
&lt;div class = "shareblock"&gt;&lt;strong&gt;Share this post:&lt;/strong&gt; &lt;a title="Email DEV102%27s+Programming+Job+Interview+Challenge+%234" href = "mailto:?body=Thought you might like this: http://honestillusion.com/blogs/blog_0/archive/2008/05/23/dev102-s-programming-job-interview-challenge-4.aspx&amp;subject=DEV102%27s+Programming+Job+Interview+Challenge+%234"&gt;Email it!&lt;/a&gt; | &lt;a href = "http://del.icio.us/post?url=http://honestillusion.com/blogs/blog_0/archive/2008/05/23/dev102-s-programming-job-interview-challenge-4.aspx&amp;title=DEV102%27s+Programming+Job+Interview+Challenge+%234" title="Submit DEV102%27s+Programming+Job+Interview+Challenge+%234 to del.icio.us" &gt;bookmark it!&lt;/a&gt; | &lt;a href = "http://www.digg.com/submit?url=http://honestillusion.com/blogs/blog_0/archive/2008/05/23/dev102-s-programming-job-interview-challenge-4.aspx&amp;phase=2" title="Submit DEV102%27s+Programming+Job+Interview+Challenge+%234 to digg.com"&gt;digg it!&lt;/a&gt; | &lt;a href = "http://reddit.com/submit?url=http://honestillusion.com/blogs/blog_0/archive/2008/05/23/dev102-s-programming-job-interview-challenge-4.aspx&amp;title=DEV102%27s+Programming+Job+Interview+Challenge+%234" title="Submit DEV102%27s+Programming+Job+Interview+Challenge+%234 to reddit.com"&gt;reddit!&lt;/a&gt;&lt;/div&gt;&lt;img src="http://honestillusion.com/aggbug.aspx?PostID=4766" width="1" height="1"&gt;</description><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/Code/default.aspx">Code</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/.Net/default.aspx">.Net</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/Programming/default.aspx">Programming</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/dotnet/default.aspx">dotnet</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/csharp/default.aspx">csharp</category></item><item><title>How can I easily log a message to a file for debugging purposes?</title><link>http://honestillusion.com/blogs/blog_0/archive/2008/04/16/how-can-i-easily-log-a-message-to-a-file-for-debugging-purposes.aspx</link><pubDate>Wed, 16 Apr 2008 14:06:47 GMT</pubDate><guid isPermaLink="false">0c240a87-1bdc-4d60-96f7-7d0531c1460e:4660</guid><dc:creator>James</dc:creator><slash:comments>0</slash:comments><comments>http://honestillusion.com/blogs/blog_0/comments/4660.aspx</comments><wfw:commentRss>http://honestillusion.com/blogs/blog_0/commentrss.aspx?PostID=4660</wfw:commentRss><description>
  &lt;p&gt;Today, either Bloglines.com or blogs.MSDN.com blinked, and suddenly I'm seeing old entries on the 'C# Frequently Asked Questions' blog as new.  No one has posted anything there in over two years. &lt;/p&gt; &lt;p&gt;Anyway, reading the most recent message, it offered a method for logging a message.  Now, ignoring side debates over log4net vs nLog vs. the Event log vs. Trace, and just concentrating on the code post --- It's not very good.  Look for yourself (then come back here)  &lt;a title="http://blogs.msdn.com/csharpfaq/archive/2006/03/27/562555.aspx" href="http://blogs.msdn.com/csharpfaq/archive/2006/03/27/562555.aspx"&gt;http://blogs.msdn.com/csharpfaq/archive/2006/03/27/562555.aspx&lt;/a&gt;&lt;/p&gt; &lt;p&gt;Despite being written by a C# MVP (*), it shows a lack of understanding of basic .Net library features, and well as C#.  So, I figured, I'd rewrite it.  I limited myself to taking what's there and fixing it instead of going an entirely different way (ie, log4net vs nLog vs etc).  Here's the revised code:&lt;/p&gt; &lt;div class="csharpcode"&gt;&lt;pre class="alt"&gt;&lt;span class="kwrd"&gt;using&lt;/span&gt; System.IO;&lt;/pre&gt;&lt;pre class="alt"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; LogMessageToFile(&lt;span class="kwrd"&gt;string&lt;/span&gt; msg)&lt;/pre&gt;&lt;pre&gt;{&lt;/pre&gt;&lt;pre class="alt"&gt;    &lt;span class="kwrd"&gt;string&lt;/span&gt; logFilepath = Path.Combine(Environment.GetEnvironmentVariable(&lt;span class="str"&gt;"TEMP"&lt;/span&gt;),&lt;span class="str"&gt;"My Log File.txt"&lt;/span&gt;);&lt;/pre&gt;&lt;pre&gt;    &lt;span class="kwrd"&gt;using&lt;/span&gt; (StreamWriter sw = File.AppendText(logFilepath))&lt;/pre&gt;&lt;pre class="alt"&gt;    {&lt;/pre&gt;&lt;pre&gt;        &lt;span class="kwrd"&gt;string&lt;/span&gt; logLine = String.Format(&lt;span class="str"&gt;"{0:G}: {1}."&lt;/span&gt;, DateTime.Now, msg);&lt;/pre&gt;&lt;pre class="alt"&gt;        sw.WriteLine(logLine);&lt;/pre&gt;&lt;pre&gt;    }&lt;/pre&gt;&lt;pre class="alt"&gt;}&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt; &lt;/p&gt;
&lt;p&gt;A few years ago, I bought a number of books, all with the title of same variation of "C# Cookbook".  Again, a lot of bad code.  I've been meaning to start a series of articles about revising them.....&lt;/p&gt;
&lt;p&gt; &lt;/p&gt;
&lt;p&gt;(*) Years ago, I was one of the very first C++ MVPs.  After ten years, I was dropped from the program.  Since then I've tried to become a C# MVP, without any luck. I'm beginning to get bitter about it.  ;-)&lt;/p&gt;
&lt;div class = "shareblock"&gt;&lt;strong&gt;Share this post:&lt;/strong&gt; &lt;a title="Email How+can+I+easily+log+a+message+to+a+file+for+debugging+purposes%3f" href = "mailto:?body=Thought you might like this: http://honestillusion.com/blogs/blog_0/archive/2008/04/16/how-can-i-easily-log-a-message-to-a-file-for-debugging-purposes.aspx&amp;subject=How+can+I+easily+log+a+message+to+a+file+for+debugging+purposes%3f"&gt;Email it!&lt;/a&gt; | &lt;a href = "http://del.icio.us/post?url=http://honestillusion.com/blogs/blog_0/archive/2008/04/16/how-can-i-easily-log-a-message-to-a-file-for-debugging-purposes.aspx&amp;title=How+can+I+easily+log+a+message+to+a+file+for+debugging+purposes%3f" title="Submit How+can+I+easily+log+a+message+to+a+file+for+debugging+purposes%3f to del.icio.us" &gt;bookmark it!&lt;/a&gt; | &lt;a href = "http://www.digg.com/submit?url=http://honestillusion.com/blogs/blog_0/archive/2008/04/16/how-can-i-easily-log-a-message-to-a-file-for-debugging-purposes.aspx&amp;phase=2" title="Submit How+can+I+easily+log+a+message+to+a+file+for+debugging+purposes%3f to digg.com"&gt;digg it!&lt;/a&gt; | &lt;a href = "http://reddit.com/submit?url=http://honestillusion.com/blogs/blog_0/archive/2008/04/16/how-can-i-easily-log-a-message-to-a-file-for-debugging-purposes.aspx&amp;title=How+can+I+easily+log+a+message+to+a+file+for+debugging+purposes%3f" title="Submit How+can+I+easily+log+a+message+to+a+file+for+debugging+purposes%3f to reddit.com"&gt;reddit!&lt;/a&gt;&lt;/div&gt;&lt;img src="http://honestillusion.com/aggbug.aspx?PostID=4660" width="1" height="1"&gt;</description><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/Code/default.aspx">Code</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/.Net/default.aspx">.Net</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/Programming/default.aspx">Programming</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/MVP/default.aspx">MVP</category></item><item><title>What's inside a foreach() statement?</title><link>http://honestillusion.com/blogs/blog_0/archive/2007/05/18/what-s-inside-a-foreach-statement.aspx</link><pubDate>Fri, 18 May 2007 15:31:47 GMT</pubDate><guid isPermaLink="false">0c240a87-1bdc-4d60-96f7-7d0531c1460e:4562</guid><dc:creator>James</dc:creator><slash:comments>2</slash:comments><comments>http://honestillusion.com/blogs/blog_0/comments/4562.aspx</comments><wfw:commentRss>http://honestillusion.com/blogs/blog_0/commentrss.aspx?PostID=4562</wfw:commentRss><description>
  &lt;p&gt;Recently I was looking at some C# code where the author, to loop through some collection,  would frequently use call GetEnumerator() and the manually step through the collections, calling MoveNext().  It seemed to me that the code could be written more cleanly using a foreach.   I got to wondering it the author knew some funky optimization detail, that I didn't, that made his code more efficient.&lt;/p&gt; &lt;p&gt;So I tried an experiment.  I wrote two methods: one, a lightly adapter version of the code I had been studying; and the other, the equivalent code, using a foreach.  I compiled them, and examined the generated IL in Reflector.&lt;/p&gt; &lt;div class="csharpcode"&gt;&lt;pre class="alt"&gt;&lt;span class="kwrd"&gt;void&lt;/span&gt; Test1(Dictionary&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;, &lt;span class="kwrd"&gt;int&lt;/span&gt;&amp;gt; bag)&lt;/pre&gt;&lt;pre&gt;{&lt;/pre&gt;&lt;pre class="alt"&gt;    Dictionary&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;, &lt;span class="kwrd"&gt;int&lt;/span&gt;&amp;gt;.Enumerator enumerator = bag.GetEnumerator();&lt;/pre&gt;&lt;pre&gt;    &lt;span class="kwrd"&gt;while&lt;/span&gt; (enumerator.MoveNext())&lt;/pre&gt;&lt;pre class="alt"&gt;    {&lt;/pre&gt;&lt;pre&gt;        &lt;span class="kwrd"&gt;if&lt;/span&gt; (bag.ContainsKey(enumerator.Current.Key))&lt;/pre&gt;&lt;pre class="alt"&gt;        {&lt;/pre&gt;&lt;pre&gt;            bag.Add(enumerator.Current.Key, 5);&lt;/pre&gt;&lt;pre class="alt"&gt;        }&lt;/pre&gt;&lt;pre&gt;    }&lt;/pre&gt;&lt;pre class="alt"&gt;}&lt;/pre&gt;&lt;pre&gt; &lt;/pre&gt;&lt;pre class="alt"&gt;&lt;span class="kwrd"&gt;void&lt;/span&gt; Test2(Dictionary&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;, &lt;span class="kwrd"&gt;int&lt;/span&gt;&amp;gt; bag)&lt;/pre&gt;&lt;pre&gt;{&lt;/pre&gt;&lt;pre class="alt"&gt;    &lt;span class="kwrd"&gt;foreach&lt;/span&gt; (KeyValuePair&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;, &lt;span class="kwrd"&gt;int&lt;/span&gt;&amp;gt; item &lt;span class="kwrd"&gt;in&lt;/span&gt; bag)&lt;/pre&gt;&lt;pre&gt;    {&lt;/pre&gt;&lt;pre class="alt"&gt;        &lt;span class="kwrd"&gt;if&lt;/span&gt;(bag.ContainsKey(item.Key))&lt;/pre&gt;&lt;pre&gt;        {&lt;/pre&gt;&lt;pre class="alt"&gt;            bag.Add(item.Key, 5);&lt;/pre&gt;&lt;pre&gt;        }&lt;/pre&gt;&lt;pre class="alt"&gt;    }&lt;/pre&gt;&lt;pre&gt;}&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;I'll spare you the IL listings, but Test1() was shorter by a small amount.  More interestingly, while some parts of the IL matched in both methods, a lot was different.  I studied the code to see the variations. One difference was in Test1, get_Current() was called twice, but only once in Test2(). But, mainly, Reflector claimed the Test2 had try and finally statements, which I figured were essentially a using{} block.  After a bit of playing, I came up with this:&lt;/p&gt;
&lt;div class="csharpcode"&gt;&lt;pre class="alt"&gt;&lt;span class="kwrd"&gt;void&lt;/span&gt; Test3(Dictionary&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;, &lt;span class="kwrd"&gt;int&lt;/span&gt;&amp;gt; bag)&lt;/pre&gt;&lt;pre&gt;{&lt;/pre&gt;&lt;pre class="alt"&gt;    &lt;span class="kwrd"&gt;using&lt;/span&gt; (Dictionary&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;, &lt;span class="kwrd"&gt;int&lt;/span&gt;&amp;gt;.Enumerator enumerator = bag.GetEnumerator())&lt;/pre&gt;&lt;pre&gt;    {&lt;/pre&gt;&lt;pre class="alt"&gt;        &lt;span class="kwrd"&gt;while&lt;/span&gt; (enumerator.MoveNext())&lt;/pre&gt;&lt;pre&gt;        {&lt;/pre&gt;&lt;pre class="alt"&gt;            KeyValuePair&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;, &lt;span class="kwrd"&gt;int&lt;/span&gt;&amp;gt; item = enumerator.Current;&lt;/pre&gt;&lt;pre&gt;            &lt;span class="kwrd"&gt;if&lt;/span&gt; (bag.ContainsKey(item.Key))&lt;/pre&gt;&lt;pre class="alt"&gt;            {&lt;/pre&gt;&lt;pre&gt;                bag.Add(item.Key, 5);&lt;/pre&gt;&lt;pre class="alt"&gt;            }&lt;/pre&gt;&lt;pre&gt;        }&lt;/pre&gt;&lt;pre class="alt"&gt;    }&lt;/pre&gt;&lt;pre&gt;}&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;Except for a few insignificant deviations (the order of temporaries on the stack, the placement of NOP instructions), Test2 &amp;amp; Test3 produce identical IL code.  More interesting, if I ask Reflector to disassemble the assembly into C# code, it displays identical foreach loops for both methods.  &lt;/p&gt;
&lt;p&gt;So, what have we learned from this?  Well, a simply manual GetEnumerator loop will end up skipping the call to Enumerator.Dispose().  Whether that is an optimization or a bug depends on your code.  And, if you're not careful, you'll probably end up retrieving the Current property more than you need to.&lt;/p&gt;
&lt;p&gt;In the end, you're probably better off calling foreach, which, one suspects, is why it was added to the language in the first place.&lt;/p&gt;
&lt;p&gt; &lt;/p&gt;&lt;a href="http://www.dotnetkicks.com/kick/?url=http://honestillusion.com/blogs/blog_0/archive/2007/05/18/what-s-inside-a-foreach-statement.aspx"&gt;&lt;img alt="kick it on DotNetKicks.com" src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://honestillusion.com/blogs/blog_0/archive/2007/05/18/what-s-inside-a-foreach-statement.aspx" border="0" /&gt;&lt;/a&gt;
&lt;div class = "shareblock"&gt;&lt;strong&gt;Share this post:&lt;/strong&gt; &lt;a title="Email What%27s+inside+a+foreach()+statement%3f" href = "mailto:?body=Thought you might like this: http://honestillusion.com/blogs/blog_0/archive/2007/05/18/what-s-inside-a-foreach-statement.aspx&amp;subject=What%27s+inside+a+foreach()+statement%3f"&gt;Email it!&lt;/a&gt; | &lt;a href = "http://del.icio.us/post?url=http://honestillusion.com/blogs/blog_0/archive/2007/05/18/what-s-inside-a-foreach-statement.aspx&amp;title=What%27s+inside+a+foreach()+statement%3f" title="Submit What%27s+inside+a+foreach()+statement%3f to del.icio.us" &gt;bookmark it!&lt;/a&gt; | &lt;a href = "http://www.digg.com/submit?url=http://honestillusion.com/blogs/blog_0/archive/2007/05/18/what-s-inside-a-foreach-statement.aspx&amp;phase=2" title="Submit What%27s+inside+a+foreach()+statement%3f to digg.com"&gt;digg it!&lt;/a&gt; | &lt;a href = "http://reddit.com/submit?url=http://honestillusion.com/blogs/blog_0/archive/2007/05/18/what-s-inside-a-foreach-statement.aspx&amp;title=What%27s+inside+a+foreach()+statement%3f" title="Submit What%27s+inside+a+foreach()+statement%3f to reddit.com"&gt;reddit!&lt;/a&gt;&lt;/div&gt;&lt;img src="http://honestillusion.com/aggbug.aspx?PostID=4562" width="1" height="1"&gt;</description><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/Code/default.aspx">Code</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/.Net/default.aspx">.Net</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/Programming/default.aspx">Programming</category></item><item><title>Design Patterns: Thoughts on the Singleton Pattern</title><link>http://honestillusion.com/blogs/blog_0/archive/2007/03/13/design-patterns-thoughts-on-the-singleton-pattern.aspx</link><pubDate>Tue, 13 Mar 2007 20:27:52 GMT</pubDate><guid isPermaLink="false">0c240a87-1bdc-4d60-96f7-7d0531c1460e:4478</guid><dc:creator>James</dc:creator><slash:comments>2</slash:comments><comments>http://honestillusion.com/blogs/blog_0/comments/4478.aspx</comments><wfw:commentRss>http://honestillusion.com/blogs/blog_0/commentrss.aspx?PostID=4478</wfw:commentRss><description>
  &lt;p&gt;(Note: I started writing this a couple days ago --- a short while before Andrew Matthews published his own very similar &lt;a href="http://aabs.wordpress.com/2007/03/08/singleton-%e2%80%93-the-most-overused-pattern/"&gt;article&lt;/a&gt;.  He, of course, finished his first...)&lt;/p&gt; &lt;p&gt;(Update: Fixed the spelling/grammar, and then wrote a bit more)&lt;/p&gt; &lt;p&gt;Lately on some of the blogs I read, I've been seeing  people giving code implementing various Design Patterns.  Much of it, I thought, wasn't particularly good, so I figured I'd inflected the blogosphere with my takes on some of them.&lt;/p&gt; &lt;p&gt;I'll start with everyone's favorite Pattern : The Singleton.&lt;/p&gt; &lt;p&gt;However, before I get to code, I figure I should give some principles for proper use:&lt;/p&gt; &lt;p&gt;&lt;strong&gt;1. You will, almost certainly, never actually need a singleton.&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;Singletons are, by far, the most overused, misused, and generally abused Design Pattern.  &lt;/p&gt; &lt;p&gt;&lt;strong&gt;2. The Singleton pattern is used to model objects of which there &lt;em&gt;can be&lt;/em&gt; only one (in the universe).  It is not intended for objects for which you &lt;em&gt;happen to need&lt;/em&gt; only one in your program.&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;For example, some might want to create a singleton for "currently logged-in user", based on the idea that can only be one "currently logged-in user".  But no.  There are many users, one just happens to be logged in now.  That is not a place not a singleton.&lt;/p&gt; &lt;p&gt;If you have just one of an object, and you want to make sure that when you reference that object anywhere in your program, you refer specifically to that one object, you do &lt;em&gt;not&lt;/em&gt; need a singleton.  What you want is a completely different programming technique known as a G&lt;em&gt;lobal Variable.&lt;/em&gt;  &lt;/p&gt; &lt;p&gt;"Wait a minute", you say.  "Aren't global variables &lt;em&gt;evil&lt;/em&gt;?"&lt;/p&gt; &lt;p&gt;Well, not exactly evil, but they are definitely frowned upon, and they will definitely cause problems if they are not handled properly.  However, the important point here is that regardless of how you refer to your global variable -- whether it's as "&lt;font face="Courier New"&gt;g_MyVar"&lt;/font&gt;  or "&lt;font face="Courier New"&gt;pMasterPtr-&amp;gt;pMyStructPtr-&amp;gt;MyVar&lt;/font&gt;" or "&lt;font face="Courier New"&gt;CMySingleton.Instance().MyVar&lt;/font&gt;" -- It's &lt;em&gt;still &lt;/em&gt;a global variable and will still have all the problems associated with one.  If you are going to have to deal with all those problems anyway, you might as well choose the method which is both the most easily understood, most efficient, and requires the least typing.&lt;/p&gt; &lt;p&gt;&lt;strong&gt;Side Note:&lt;/strong&gt; The second example of "renamed global variables" above came from an actual C program I was involved with some years ago.  pMasterPtr pointed to a (malloc'ed) struct, which was just a collection of pointers to other malloc'ed structs (one of each).  The elements of these structs had nothing to do with each, beyond the fact that they were all associated with a particular module.  The project leader proudly announced that the program had "only one global variable".  On program start-up, the "Structure Allocated Assignment Block" (i.e., SAAB, named after my car, over my objections) was malloc'ed, and then assigned to pMasterPtr (which I think was actually called pSAAB), then the other struct were malloc'ed and their pointers stored in the SAAB.  We could have just as easily made the elements of the secondary structs, elements of the primary struct, or just plain hard allocated data items, and it would have have no effect on the program --- the only difference is that this plan allowed the boss to say it had "only one global variable" --- which is, of course, nonsense -- it had dozens, they just had awkward names.  Additionally, due to a over-eager company coding policy, every access to a pointer had to be proceeded by a check if it were NULL, so, we'd have long blocks of code like this:&lt;/p&gt; &lt;blockquote&gt;&lt;pre class="code"&gt;&lt;span&gt;if&lt;/span&gt; (pSAAB == NULL)
{
    PrintErrorMessage();
    &lt;span&gt;return&lt;/span&gt;;
}
&lt;span&gt;if&lt;/span&gt; (pSAAB-&amp;gt;pIOStruct == NULL)
{
    PrintErrorMessage();
    &lt;span&gt;return&lt;/span&gt;;
}
pSAAB-&amp;gt;pIOStruct-&amp;gt;nColor = NewColor;&lt;/pre&gt;&lt;/blockquote&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;When actually a simple line like this would have sufficed:&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;font face="Courier New"&gt;g_nIOColor = NewColor;&lt;/font&gt;&lt;/p&gt;&lt;/blockquote&gt;
&lt;p&gt;The point of all the was to show to what great length some programmers would go to, to pretend that they don't use global variables.   And this leads directly to our obsession with, and abuse of, singletons.&lt;/p&gt;
&lt;p&gt;Now, when you find something in your application of which there &lt;em&gt;Can Be Only One&lt;/em&gt;, such as the Screen or the Mouse or the Keyboard, then you have a place for a singleton.  And in these cases, in .Net, I suggest using a static class.&lt;/p&gt;
&lt;p&gt;"Wait a minute", you say.  "Aren't static classes as singletons &lt;em&gt;evil&lt;/em&gt;?"&lt;/p&gt;
&lt;p&gt;Well, not exactly evil, but they are definitely frowned upon, mainly because they aren't inherently thread-safe.  However, no singleton technique is inherently thread-safe.  The methods of making a singleton and serializing access are completely separate.  The basic logic here is that if you are going to go to the trouble of allocating a singleton, it's easy to remember to also add the code to serialize access, but if you're going to take the easy way out on the singleton, you'll probably forget about synchronization also.  Not a particularly rational design strategy, but we haven't talked about a rational design policy yet in this article.&lt;/p&gt;
&lt;p&gt;So, we've created the static class, and carefully implement thread-safe access, now do we have a good case for a singleton.  Still, no.  Because, as I pointed out earlier, a singleton is just a special kind of global variable.  Which means it has all the problems of a global variable. For instance, going back to another earlier example, the currently logged on user.  This appears to be a perfect candidate for a global variable if not actually a singleton.  And it was in that light the High-Priced Consultant Who Was Designing The System (on another project I worked on years ago -  C++ this time), decided that there would be "just a handful" of global variables in the app, one of which was "CurrentUser".  And I immediately protested -- I was assigned to write the administration module, where an admin user could log-in and &lt;em&gt;impersonate &lt;/em&gt;another user.  Hence many (most) of the tasks in the app was to perform had to be done for &lt;em&gt;this specified user,&lt;/em&gt;  who is not necessarily the (singular) CurrentUser.  Nevertheless, everyone else on the team used the global CurrentUser throughout the app, and I was forced to re-write much of it, to pass EffectiveUser as a parameter.&lt;/p&gt;
&lt;p&gt;"Wait a minute", you say.  "Aren't you talking about a global variable, not a singleton?"  Yes, but the same rules apply.  Consider the examples I gave before of true singletons: the Screen, or the Mouse or the Keyboard.  Can you say for sure that you application will only ever have to deal with one of each of them?  Multiple monitors are already quite fashionable, and in this connected world, having a local user &amp;amp; a remote user, sharing one screen but each with their own mouse &amp;amp; keyboard isn't that unusual.&lt;/p&gt;
&lt;p&gt; &lt;/p&gt;&lt;a href="http://www.dotnetkicks.com/kick/?url=http://honestillusion.com/blogs/blog_0/archive/2007/03/13/design-patterns-thoughts-on-the-singleton-pattern.aspx"&gt;&lt;img alt="kick it on DotNetKicks.com" src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://honestillusion.com/blogs/blog_0/archive/2007/03/13/design-patterns-thoughts-on-the-singleton-pattern.aspx" border="0" /&gt;&lt;/a&gt;
&lt;div class = "shareblock"&gt;&lt;strong&gt;Share this post:&lt;/strong&gt; &lt;a title="Email Design+Patterns%3a+Thoughts+on+the+Singleton+Pattern" href = "mailto:?body=Thought you might like this: http://honestillusion.com/blogs/blog_0/archive/2007/03/13/design-patterns-thoughts-on-the-singleton-pattern.aspx&amp;subject=Design+Patterns%3a+Thoughts+on+the+Singleton+Pattern"&gt;Email it!&lt;/a&gt; | &lt;a href = "http://del.icio.us/post?url=http://honestillusion.com/blogs/blog_0/archive/2007/03/13/design-patterns-thoughts-on-the-singleton-pattern.aspx&amp;title=Design+Patterns%3a+Thoughts+on+the+Singleton+Pattern" title="Submit Design+Patterns%3a+Thoughts+on+the+Singleton+Pattern to del.icio.us" &gt;bookmark it!&lt;/a&gt; | &lt;a href = "http://www.digg.com/submit?url=http://honestillusion.com/blogs/blog_0/archive/2007/03/13/design-patterns-thoughts-on-the-singleton-pattern.aspx&amp;phase=2" title="Submit Design+Patterns%3a+Thoughts+on+the+Singleton+Pattern to digg.com"&gt;digg it!&lt;/a&gt; | &lt;a href = "http://reddit.com/submit?url=http://honestillusion.com/blogs/blog_0/archive/2007/03/13/design-patterns-thoughts-on-the-singleton-pattern.aspx&amp;title=Design+Patterns%3a+Thoughts+on+the+Singleton+Pattern" title="Submit Design+Patterns%3a+Thoughts+on+the+Singleton+Pattern to reddit.com"&gt;reddit!&lt;/a&gt;&lt;/div&gt;&lt;img src="http://honestillusion.com/aggbug.aspx?PostID=4478" width="1" height="1"&gt;</description><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/Code/default.aspx">Code</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/.Net/default.aspx">.Net</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/Programming/default.aspx">Programming</category></item><item><title>More Fun with C# Iterators: Take, Skip, TakeWhile, SkipWhile</title><link>http://honestillusion.com/blogs/blog_0/archive/2007/03/09/more-fun-with-c-iterators-take-skip-takewhile-skipwhile.aspx</link><pubDate>Sat, 10 Mar 2007 00:04:16 GMT</pubDate><guid isPermaLink="false">0c240a87-1bdc-4d60-96f7-7d0531c1460e:4474</guid><dc:creator>James</dc:creator><slash:comments>4</slash:comments><comments>http://honestillusion.com/blogs/blog_0/comments/4474.aspx</comments><wfw:commentRss>http://honestillusion.com/blogs/blog_0/commentrss.aspx?PostID=4474</wfw:commentRss><description>
  &lt;p&gt;As I was reading &lt;a href="http://gbarnett.org/archive/2007/03/08/linq-standard-query-operators-part-3.aspx"&gt;this article by Granville Barnett&lt;/a&gt; on some of the new operators available on LINQ queries, I thought, "That's all well and good, but for the time being, we're living in a .Net 2.0 world.  I wonder if I could emulate those with just generics &amp;amp; iterators?"  As it turned out, it was quite easy.&lt;/p&gt; &lt;p&gt;First up is Take:  Given a collection, we want to return the subset which is just the first N items.  To handle this, we just return items while counting down to zero. When we reach zero, we stop.  &lt;/p&gt; &lt;p&gt; &lt;/p&gt;&lt;div class="csharpcode"&gt;&lt;pre class="alt"&gt;        &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;public&lt;/span&gt; IEnumerable&amp;lt;T&amp;gt; Take&amp;lt;T&amp;gt;(IEnumerable&amp;lt;T&amp;gt; enm, &lt;span class="kwrd"&gt;int&lt;/span&gt; take)&lt;/pre&gt;&lt;pre&gt;        {&lt;/pre&gt;&lt;pre class="alt"&gt;            &lt;span class="kwrd"&gt;foreach&lt;/span&gt; (T t &lt;span class="kwrd"&gt;in&lt;/span&gt; enm)&lt;/pre&gt;&lt;pre&gt;            {&lt;/pre&gt;&lt;pre class="alt"&gt;                &lt;span class="kwrd"&gt;if&lt;/span&gt; (take-- == 0)&lt;/pre&gt;&lt;pre&gt;                    &lt;span class="kwrd"&gt;break&lt;/span&gt;;&lt;/pre&gt;&lt;pre class="alt"&gt;                &lt;span class="kwrd"&gt;yield&lt;/span&gt; &lt;span class="kwrd"&gt;return&lt;/span&gt; t;&lt;/pre&gt;&lt;pre&gt;            } &lt;span class="rem"&gt;// foreach &lt;/span&gt;&lt;/pre&gt;&lt;pre class="alt"&gt;         }&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;&lt;/p&gt;
&lt;p&gt;
&lt;/p&gt;&lt;div class="csharpcode"&gt;&lt;pre class="alt"&gt;            &lt;span class="kwrd"&gt;string&lt;/span&gt;[] peopleinit = &lt;span class="kwrd"&gt;new&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt;[] { &lt;span class="str"&gt;"Granville"&lt;/span&gt;, &lt;span class="str"&gt;"Rachel"&lt;/span&gt;, &lt;span class="str"&gt;"Monica"&lt;/span&gt;, &lt;span class="str"&gt;"John"&lt;/span&gt;, &lt;span class="str"&gt;"Ross"&lt;/span&gt;, &lt;span class="str"&gt;"Joey"&lt;/span&gt; };&lt;/pre&gt;&lt;pre&gt;            List&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt; people = &lt;span class="kwrd"&gt;new&lt;/span&gt; List&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt;(peopleinit);&lt;/pre&gt;&lt;pre class="alt"&gt; &lt;/pre&gt;&lt;pre&gt;            Console.WriteLine(&lt;span class="str"&gt;"Take Test...."&lt;/span&gt;);&lt;/pre&gt;&lt;pre class="alt"&gt;            &lt;span class="kwrd"&gt;foreach&lt;/span&gt; (&lt;span class="kwrd"&gt;string&lt;/span&gt; person &lt;span class="kwrd"&gt;in&lt;/span&gt; Iter.Take(people, 2))&lt;/pre&gt;&lt;pre&gt;            {&lt;/pre&gt;&lt;pre class="alt"&gt;                Console.WriteLine(person);   &lt;span class="rem"&gt;// Prints  Granville, Rachel&lt;/span&gt;&lt;/pre&gt;&lt;pre&gt;            }&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;&lt;/p&gt;
&lt;p&gt;Next, is Skip.  This is essentially the reverse of Take: Given a collection, we want to return the subset which is everything after the first N items.  And handling Skip is essnetially the reverse of Take as well:  We still count down to zero as we iterator through the collection, but we don't return anything until we reach zero.  (Of course, after we reach zero, we have to stop decrementing the count, or the if() will fail when skip equal -1.)&lt;/p&gt;
&lt;p&gt;
&lt;/p&gt;&lt;div class="csharpcode"&gt;&lt;pre class="alt"&gt;&lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;public&lt;/span&gt; IEnumerable&amp;lt;T&amp;gt; Skip&amp;lt;T&amp;gt;(IEnumerable&amp;lt;T&amp;gt; enm, &lt;span class="kwrd"&gt;int&lt;/span&gt; skip)&lt;/pre&gt;&lt;pre&gt;{&lt;/pre&gt;&lt;pre class="alt"&gt;    &lt;span class="kwrd"&gt;foreach&lt;/span&gt; (T t &lt;span class="kwrd"&gt;in&lt;/span&gt; enm)&lt;/pre&gt;&lt;pre&gt;    {&lt;/pre&gt;&lt;pre class="alt"&gt;        &lt;span class="kwrd"&gt;if&lt;/span&gt; (skip == 0)&lt;/pre&gt;&lt;pre&gt;            &lt;span class="kwrd"&gt;yield&lt;/span&gt; &lt;span class="kwrd"&gt;return&lt;/span&gt; t;&lt;/pre&gt;&lt;pre class="alt"&gt;        &lt;span class="kwrd"&gt;else&lt;/span&gt;&lt;/pre&gt;&lt;pre&gt;            --skip;&lt;/pre&gt;&lt;pre class="alt"&gt;    } &lt;span class="rem"&gt;// foreach &lt;/span&gt;&lt;/pre&gt;&lt;pre&gt;}&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;&lt;/p&gt;
&lt;p&gt;
&lt;/p&gt;&lt;div class="csharpcode"&gt;&lt;pre class="alt"&gt;Console.WriteLine(&lt;span class="str"&gt;"Skip Test...."&lt;/span&gt;);&lt;/pre&gt;&lt;pre&gt;&lt;span class="kwrd"&gt;foreach&lt;/span&gt; (&lt;span class="kwrd"&gt;string&lt;/span&gt; person &lt;span class="kwrd"&gt;in&lt;/span&gt; Iter.Skip(people, 4))&lt;/pre&gt;&lt;pre class="alt"&gt;{&lt;/pre&gt;&lt;pre&gt;    Console.WriteLine(person);   &lt;span class="rem"&gt;// Prints  Ross, Joey&lt;/span&gt;&lt;/pre&gt;&lt;pre class="alt"&gt;}&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;&lt;/p&gt;
&lt;p&gt;Now, once we have Skip, SkipFirst (&lt;a href="http://honestillusion.com/blogs/blog_0/archive/2007/02/05/c-code-adding-skip-first-to-foreach.aspx"&gt;which we discussed before)&lt;/a&gt; just become an instance of that. &lt;/p&gt;
&lt;p&gt;
&lt;/p&gt;&lt;div class="csharpcode"&gt;&lt;pre class="alt"&gt;&lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;public&lt;/span&gt; IEnumerable&amp;lt;T&amp;gt; SkipFirst&amp;lt;T&amp;gt;(IEnumerable&amp;lt;T&amp;gt; enm)&lt;/pre&gt;&lt;pre&gt;{&lt;/pre&gt;&lt;pre class="alt"&gt;    &lt;span class="kwrd"&gt;return&lt;/span&gt; Skip(enm, 1);&lt;/pre&gt;&lt;pre&gt;} &lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;&lt;/p&gt;
&lt;p&gt;There is no simple way to expand SkipLast, which was also discussed in that previous article, beyond just one item, so we'll leave it's implementation.&lt;/p&gt;
&lt;p&gt;A bit more advanced are TakeWhile and SkipWhile.  And, unlike the LINQ versions, we can't use lambda expression, so we'll have to make do with delagates.&lt;/p&gt;
&lt;p&gt;The essense of TakeWhile is, given a collection, we return items until we reach one which fails a given predicate.  Note that we stop at the first failure we reach (even if there may be later item which pass the predicate test)&lt;/p&gt;
&lt;p&gt;
&lt;/p&gt;&lt;div class="csharpcode"&gt;&lt;pre class="alt"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;delegate&lt;/span&gt; &lt;span class="kwrd"&gt;bool&lt;/span&gt; whilecond&amp;lt;T&amp;gt;(T t);&lt;/pre&gt;&lt;pre&gt; &lt;/pre&gt;&lt;pre class="alt"&gt;&lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;public&lt;/span&gt; IEnumerable&amp;lt;T&amp;gt; TakeWhile&amp;lt;T&amp;gt;(IEnumerable&amp;lt;T&amp;gt; enm, whilecond&amp;lt;T&amp;gt; take)&lt;/pre&gt;&lt;pre&gt;{&lt;/pre&gt;&lt;pre class="alt"&gt;      &lt;span class="kwrd"&gt;foreach&lt;/span&gt; (T t &lt;span class="kwrd"&gt;in&lt;/span&gt; enm)&lt;/pre&gt;&lt;pre&gt;    {&lt;/pre&gt;&lt;pre class="alt"&gt;        &lt;span class="kwrd"&gt;if&lt;/span&gt; (take(t))&lt;/pre&gt;&lt;pre&gt;            &lt;span class="kwrd"&gt;yield&lt;/span&gt; &lt;span class="kwrd"&gt;return&lt;/span&gt; t;&lt;/pre&gt;&lt;pre class="alt"&gt;        &lt;span class="kwrd"&gt;else&lt;/span&gt;&lt;/pre&gt;&lt;pre&gt;            &lt;span class="kwrd"&gt;break&lt;/span&gt;;&lt;/pre&gt;&lt;pre class="alt"&gt; &lt;/pre&gt;&lt;pre&gt;    } &lt;span class="rem"&gt;// foreach &lt;/span&gt;&lt;/pre&gt;&lt;pre class="alt"&gt; &lt;/pre&gt;&lt;pre&gt;}&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;&lt;/p&gt;
&lt;p&gt;
&lt;/p&gt;&lt;div class="csharpcode"&gt;&lt;pre class="alt"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;bool&lt;/span&gt; LongerThan5(&lt;span class="kwrd"&gt;string&lt;/span&gt; a)&lt;/pre&gt;&lt;pre&gt;{&lt;/pre&gt;&lt;pre class="alt"&gt;    &lt;span class="kwrd"&gt;return&lt;/span&gt; a.Length &amp;gt; 5;&lt;/pre&gt;&lt;pre&gt;}&lt;/pre&gt;&lt;pre class="alt"&gt;        &lt;span class="rem"&gt;// :&lt;/span&gt;&lt;/pre&gt;&lt;pre&gt;        &lt;span class="rem"&gt;//:&lt;/span&gt;&lt;/pre&gt;&lt;pre class="alt"&gt;        &lt;/pre&gt;&lt;pre&gt; Console.WriteLine(&lt;span class="str"&gt;"TakeWhile Test...."&lt;/span&gt;);&lt;/pre&gt;&lt;pre class="alt"&gt;&lt;span class="kwrd"&gt;foreach&lt;/span&gt; (&lt;span class="kwrd"&gt;string&lt;/span&gt; person &lt;span class="kwrd"&gt;in&lt;/span&gt; Iter.TakeWhile(people, LongerThan5))&lt;/pre&gt;&lt;pre&gt;{&lt;/pre&gt;&lt;pre class="alt"&gt;    Console.WriteLine(person);   &lt;span class="rem"&gt;// Prints  Granville, "Rachel", "Monica", &lt;/span&gt;&lt;/pre&gt;&lt;pre&gt;}&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;&lt;/p&gt;
&lt;p&gt; &lt;/p&gt;
&lt;p&gt;Final, this brings us to SkipWhile, which is the inverse of TakeWhile:  Given a collection, we skip items until one fails a given predicate, and then we return the rest (even though some of the rest may fail the predicate)&lt;/p&gt;
&lt;p&gt;
&lt;/p&gt;&lt;div class="csharpcode"&gt;&lt;pre class="alt"&gt;&lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;public&lt;/span&gt; IEnumerable&amp;lt;T&amp;gt; SkipWhile&amp;lt;T&amp;gt;(IEnumerable&amp;lt;T&amp;gt; enm, whilecond&amp;lt;T&amp;gt; skip)&lt;/pre&gt;&lt;pre&gt;{&lt;/pre&gt;&lt;pre class="alt"&gt;    &lt;span class="kwrd"&gt;bool&lt;/span&gt; doneskipping = &lt;span class="kwrd"&gt;false&lt;/span&gt;;&lt;/pre&gt;&lt;pre&gt;    &lt;span class="kwrd"&gt;foreach&lt;/span&gt; (T t &lt;span class="kwrd"&gt;in&lt;/span&gt; enm)&lt;/pre&gt;&lt;pre class="alt"&gt;    {&lt;/pre&gt;&lt;pre&gt;        &lt;span class="kwrd"&gt;if&lt;/span&gt; (doneskipping || !skip(t))&lt;/pre&gt;&lt;pre class="alt"&gt;        {&lt;/pre&gt;&lt;pre&gt;            doneskipping = &lt;span class="kwrd"&gt;true&lt;/span&gt;;&lt;/pre&gt;&lt;pre class="alt"&gt;            &lt;span class="kwrd"&gt;yield&lt;/span&gt; &lt;span class="kwrd"&gt;return&lt;/span&gt; t;&lt;/pre&gt;&lt;pre&gt;         } &lt;span class="rem"&gt;// else&lt;/span&gt;&lt;/pre&gt;&lt;pre class="alt"&gt; &lt;/pre&gt;&lt;pre&gt;    } &lt;span class="rem"&gt;// foreach &lt;/span&gt;&lt;/pre&gt;&lt;pre class="alt"&gt;}&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;&lt;/p&gt;
&lt;p&gt;
&lt;/p&gt;&lt;div class="csharpcode"&gt;&lt;pre class="alt"&gt; &lt;/pre&gt;&lt;pre&gt;Console.WriteLine(&lt;span class="str"&gt;"SkipWhile Test...."&lt;/span&gt;);&lt;/pre&gt;&lt;pre class="alt"&gt;&lt;span class="kwrd"&gt;foreach&lt;/span&gt; (&lt;span class="kwrd"&gt;string&lt;/span&gt; person &lt;span class="kwrd"&gt;in&lt;/span&gt; Iter.SkipWhile(people, LongerThan5))&lt;/pre&gt;&lt;pre&gt;{&lt;/pre&gt;&lt;pre class="alt"&gt;    Console.WriteLine(person);   &lt;span class="rem"&gt;// Prints  "John", "Ross", "Joey" &lt;/span&gt;&lt;/pre&gt;&lt;pre&gt;}&lt;/pre&gt;&lt;/div&gt;
&lt;p&gt;&lt;/p&gt;
&lt;p&gt; &lt;/p&gt;
&lt;p&gt; &lt;/p&gt;&lt;a href="http://www.dotnetkicks.com/kick/?url=http://honestillusion.com/blogs/blog_0/archive/2007/03/09/more-fun-with-c-iterators-take-skip-takewhile-skipwhile.aspx"&gt;&lt;img alt="kick it on DotNetKicks.com" src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://honestillusion.com/blogs/blog_0/archive/2007/03/09/more-fun-with-c-iterators-take-skip-takewhile-skipwhile.aspx" border="0" /&gt;&lt;/a&gt;
&lt;div class = "shareblock"&gt;&lt;strong&gt;Share this post:&lt;/strong&gt; &lt;a title="Email More+Fun+with+C%23+Iterators%3a+Take%2c+Skip%2c+TakeWhile%2c+SkipWhile" href = "mailto:?body=Thought you might like this: http://honestillusion.com/blogs/blog_0/archive/2007/03/09/more-fun-with-c-iterators-take-skip-takewhile-skipwhile.aspx&amp;subject=More+Fun+with+C%23+Iterators%3a+Take%2c+Skip%2c+TakeWhile%2c+SkipWhile"&gt;Email it!&lt;/a&gt; | &lt;a href = "http://del.icio.us/post?url=http://honestillusion.com/blogs/blog_0/archive/2007/03/09/more-fun-with-c-iterators-take-skip-takewhile-skipwhile.aspx&amp;title=More+Fun+with+C%23+Iterators%3a+Take%2c+Skip%2c+TakeWhile%2c+SkipWhile" title="Submit More+Fun+with+C%23+Iterators%3a+Take%2c+Skip%2c+TakeWhile%2c+SkipWhile to del.icio.us" &gt;bookmark it!&lt;/a&gt; | &lt;a href = "http://www.digg.com/submit?url=http://honestillusion.com/blogs/blog_0/archive/2007/03/09/more-fun-with-c-iterators-take-skip-takewhile-skipwhile.aspx&amp;phase=2" title="Submit More+Fun+with+C%23+Iterators%3a+Take%2c+Skip%2c+TakeWhile%2c+SkipWhile to digg.com"&gt;digg it!&lt;/a&gt; | &lt;a href = "http://reddit.com/submit?url=http://honestillusion.com/blogs/blog_0/archive/2007/03/09/more-fun-with-c-iterators-take-skip-takewhile-skipwhile.aspx&amp;title=More+Fun+with+C%23+Iterators%3a+Take%2c+Skip%2c+TakeWhile%2c+SkipWhile" title="Submit More+Fun+with+C%23+Iterators%3a+Take%2c+Skip%2c+TakeWhile%2c+SkipWhile to reddit.com"&gt;reddit!&lt;/a&gt;&lt;/div&gt;&lt;img src="http://honestillusion.com/aggbug.aspx?PostID=4474" width="1" height="1"&gt;</description><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/Code/default.aspx">Code</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/.Net/default.aspx">.Net</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/Programming/default.aspx">Programming</category><category domain="http://honestillusion.com/blogs/blog_0/archive/tags/Generics+without+Collections/default.aspx">Generics without Collections</category></item></channel></rss>