I recently attended a meeting of the Dallas

C# SIG, a group which I hadn’t attended in quite some time, because they had Adam

Keyscome in to talk about Ruby. I don’t live under a rock, so I’ve

heard the buzz about Ruby but I hadn’t spent much timelooking into it because

it wasn’t immensely relevant to my day to day. That said,this was a great

chanceto learn soI checked out the meeting and I must admit, I was impressed.

I’m hardly a convert but I can understand Adam’s point that Ruby “feels” moreenjoyable

towrite for him.

While most things Ruby can do I think C# 3.0 has well in hand, therestill some

things C# can’t do yet. The dynamic augmentation of an instance, not a type,

is intriguing to me and certainly powerful. One featurethat I thought

was interesting, and immediately doable in C# 3.0 was the way Ruby can handle loops.

For instance take this Ruby code (syntax errors possible,this is not checked)

:

50.Times do
  Puts "We

Built This City ..."
  Puts "We

Built This City ..."
  Puts "On

Rock And Roll"
end

I like this much better than the standard C# syntax of a For loop because it focuses

on what is important. Its terse yet clear, and I wanted in C# 3.0 right now,

so here it is:


              public

              static

              class LoopingExtensions
{

              public

              static

              void Times(thisint upperBound,

Action<int> action)
    {

              for (int index

= 0; index < upperBound; index++)
            action.Invoke(index);
    }
}

This results in a very nice piece of C# code, equivalent to our Ruby example above:

50.Times(i => {
    Console.WriteLine("We

Built This City...");
    Console.WriteLine("We

Built This City...");
    Console.WriteLine("On

Rock And Roll");
}

Simply enough to implement, and a great example of using Lambda expressions and extension

methods to improve the readability of your code.